﻿Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.Net
Imports System.Xml
Imports IMDBDLL
Imports System.Threading

Public Class Form1
#Region "Declare variables"
    Private createdImage As Bitmap
    Private createdCover As Bitmap
    Private bLoaded As Boolean = False
    Private currentDoc As XDocument
    Private sImgUrl As String = "http://images.themoviedb.org/backdrops/"
    Private sImgUrlPoster As String = "http://images.themoviedb.org/posters/"
    Private direcListBatch() As String
    Private Const API_KEY = "4206fed45ea3aa91848ce3447c217663"
    Private direcList() As String
    Dim aryBackdrops As New List(Of KeyValuePair(Of Bitmap, String))
    Dim aryPosters As New List(Of KeyValuePair(Of Bitmap, String))
    Dim resetEvents() As Threading.ManualResetEvent
    Dim resetEventsPoster() As Threading.ManualResetEvent
    Private currentTitle As IMDbTitle
    Private bNotFoundOnMovieDB As Boolean = False
    Private bNotFoundOnIMDB As Boolean = True
    Private sCurrentBatchMovie As String = ""
    Private bmpAudioFormat As Bitmap
    Private bmpVideoResolution As Bitmap
    Private currentBatchDirec As String
    Private sDefaultTemplatePath As String = ""
    Private sActors As String = ""
    Private sGenres As String = ""
    Private sDirectors As String = ""
    Private bmpBatchBackdrop As Bitmap = Nothing
    Private iRetryCount As Integer = 0
    Dim bmpFanArt1, bmpFanArt2, bmpFanArt3 As Bitmap
    Dim iFanartCount As Integer = 0
#End Region
#Region "Declare IMDB methods"
    Public Delegate Sub functionCall(ByVal type As Integer, ByVal result As Object)
    Public Delegate Sub BatchFunctionCall(ByVal type As Integer, ByVal result As Object)
    ''' <summary>
    ''' Delegate to call the errorHandler.
    ''' </summary>
    ''' <param name="exc">The Exception.</param>
    Public Delegate Sub errorCall(ByVal exc As Exception)
    Public Delegate Sub BatchErrorCall(ByVal exc As Exception)

    ''' <summary>
    ''' Delegate to call the progressUpdater.
    ''' </summary>
    ''' <param name="value">Value to add to the progress bar.</param>
    Public Delegate Sub progressCall(ByVal value As Integer)
    Public Delegate Sub BatchProgressCall(ByVal value As Integer)

    ''' <summary>
    ''' Event of functionCall.
    ''' </summary>
    Private formFunctionCaller As functionCall
    Private formBatchFunctionCaller As BatchFunctionCall

    ''' <summary>
    ''' Event of errorCall.
    ''' </summary>
    Private formErrorCaller As errorCall
    Private formBatchErrorCaller As BatchErrorCall

    ''' <summary>
    ''' Event of progressCall.
    ''' </summary>
    Private formProgressCaller As progressCall
    Private formBatchProgressCaller As BatchProgressCall
    Private [error] = False
    Private imdbMgr As IMDbManager
    Private imdbBatchMgr As IMDbManager
#End Region

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Try

        
            loadSettings()
            pbExistingSheet.Location = New Point(197, 4)
            pbExistingSheet.Size = New Size(960, 540)
            pbExistingSheet.Visible = False
            If Environment.GetCommandLineArgs.Length > 1 Then
                Dim retValue = Environment.GetCommandLineArgs
                Dim sMovieName = retValue(1)
                Dim sDirectory = retValue(2)
                'silent mode
                Me.Visible = False
                generateSilent(sDirectory, sMovieName)
                Application.Exit()
            Else

                If My.Settings.DefaultFolder <> vbNullString Then
                    txtManualFolderSelection.Text = My.Settings.DefaultFolder
                    populateMovieList()
                    txtBatchProcess.Text = My.Settings.DefaultFolder
                    populateMovieListBatch()
                    FileSystemWatcher1.Path = My.Settings.DefaultFolder
                End If





            End If
            formFunctionCaller = New functionCall(AddressOf processResult)
            formErrorCaller = (New errorCall(AddressOf ErrorHandler))
            formProgressCaller = (New progressCall(AddressOf progressUpdater))
            'set up events for batch mode
            formBatchFunctionCaller = New BatchFunctionCall(AddressOf BatchProcessResult)
            formBatchErrorCaller = (New BatchErrorCall(AddressOf BatchErrorHandler))
            formBatchProgressCaller = (New BatchProgressCall(AddressOf BatchProgressUpdater))
            loadSavedTemplates()
            lblVersion.Text = "Version " & System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()
            cboTemplates.DataSource = lstTemplates.Items
            cboTemplates.DisplayMember = "Text"
            cboApplyNewTemplate.DataSource = lstTemplates.Items
            cboApplyNewTemplate.DisplayMember = "Text"
            pnlCreateSheet.Controls.Remove(pnlMovieInfo)
            Me.Controls.Add(pnlMovieInfo)
            pnlMovieInfo.Location = New Point(701, 50)
        Catch ex As Exception
            MessageBox.Show("Unable to locate you default folder.")
            txtManualFolderSelection.Text = ""
        End Try
    End Sub
#Region "IMDB Events"
    Sub progressUpdater(ByVal value As Integer)

    End Sub
    Sub ErrorHandler(ByVal exc As Exception)
        [error] = True
        If exc.Message = "No results found!" Then
            LogManual("Cannot find current movie on IMDB")
            'check movie db.org and if present there get imdb id
            Dim s As KeyValuePair(Of String, String)
            s = lstMovies.SelectedItem
            Dim imdbID As String = ""
            imdbID = searchForMovieIMDBId(s.Value)
            If bNotFoundOnIMDB And bNotFoundOnMovieDB Then
                LogManual("Movie could not be found on IMDB or theMovieDB.org.Your out of luck mate.")
            Else
                If imdbID <> "0" Then
                    LogManual("Movie found on TheMovieDB.org. Using IMDB ID to lookup movie info on IMDB")
                    searchIMDB(imdbID, 1)
                Else
                    bNotFoundOnIMDB = True
                    LogManual("No IMDB ID found for this movie. Using TheMovieDB.org to get information.")
                    searchForMovie(s.Value)
                End If
            End If
        End If

    End Sub
    Sub processResult(ByVal type As Integer, ByVal result As Object)
        If [error] = False Then
            'exact match so title is returned directly
            If type = 0 Then
                currentTitle = CType(result, IMDbTitle)
                LogManual("Found IMDB Match " & currentTitle.Title & " (" & currentTitle.Year & ")")

                populateBackdropsIMDB(currentTitle.ID)
                populatePosters()
                populateMovieInfo()
            Else
                Dim listResults = CType(result, List(Of IMDbLink))
                If listResults.Count = 1 Then
                    'only one result so no point in showing multiple selection screen
                    imdbMgr.IMDbParse(listResults(0).URL)
                    btnMoreFound.Visible = False
                Else
                    Dim list = CType(result, List(Of IMDbLink))

                    Results.getInstance.setResults(result)
                    btnMoreFound.Visible = True
                    btnMoreFound.Text = list.Count - 1 & " More Found..."
                    'If Results.getInstance.ShowDialog = Windows.Forms.DialogResult.OK Then
                    '    imdbMgr.IMDbParse(Results.getInstance.Selected)
                    'End If
                    imdbMgr.IMDbParse(list(0).URL)
                End If
            End If
        End If
    End Sub
#End Region
#Region "Batch Events"
    Sub BatchProgressUpdater(ByVal value As Integer)
    End Sub
    Sub BatchErrorHandler(ByVal exc As Exception)
        [error] = True
        If exc.Message = "No results found!" Then
            Log("Cannot find current movie on IMDB")
            'check movie db.org and if present there get imdb id
            
            Dim imdbID As String = ""
            imdbID = searchForMovieIMDBId(sCurrentBatchMovie)
            If bNotFoundOnIMDB And bNotFoundOnMovieDB Then
                Log("Movie could not be found on IMDB or theMovieDB.org.Your out of luck mate.")
            Else
                If imdbID <> "0" Then
                    Log("Movie found on TheMovieDB.org. Using IMDB ID to lookup movie info on IMDB")
                    searchIMDBBatch(imdbID, 1)
                Else
                    bNotFoundOnIMDB = True
                    Log("No IMDB ID found for this movie. Using TheMovieDB.org to get information.")
                    searchForMovie(sCurrentBatchMovie)
                End If
            End If
        End If
        Application.DoEvents()
    End Sub
    Sub BatchProcessResult(ByVal type As Integer, ByVal result As Object)
        If [error] = False Then
            'exact match so title is returned directly
            If type = 0 Then
                currentTitle = CType(result, IMDbTitle)
                Log("Found IMDB Match " & currentTitle.Title & " (" & currentTitle.Year & ")")
                getMovieInfoIMDB(currentTitle)
            Else
                Dim listResults = CType(result, List(Of IMDbLink))
                imdbBatchMgr.IMDbParse(listResults(0).URL)
            End If
        End If
        Application.DoEvents()
    End Sub
#End Region

    Private Sub loadSettings()
        Try
            chkIncludeCover.Checked = My.Settings.IncludeCover
            chkIncludeRating.Checked = My.Settings.IncludeRating
            chkIncludeRuntime.Checked = My.Settings.IncludeRuntime
            chkIncludeSummary.Checked = My.Settings.IncludeSummary
            chkIncludeTitle.Checked = My.Settings.IncludeTitle
            txtMovieSheetName.Text = My.Settings.MovieSheetName
            txtCoverName.Text = My.Settings.CoverName
            txtCoverHeight.Text = My.Settings.CoverHeight.ToString
            txtCoverWidth.Text = My.Settings.CoverWidth.ToString
            txtDefaultBackdrop.Text = My.Settings.DefaultBackdrop
            If My.Settings.PrimarySource = "IMDB" Then
                optIMDB.Checked = True
            Else
                optMovieDB.Checked = True
            End If
            If My.Settings.AnalyseMKVs = True Then
                optEnabled.Checked = True
            Else
                optDisabled.Checked = True
            End If
            txt1080.Text = My.Settings.p1080
            txt720.Text = My.Settings.p720
            txtDolbyDigital.Text = My.Settings.DolbyPath
            txtDTS.Text = My.Settings.DTSPath
            txtDVDIcon.Text = My.Settings.DVDPath
            txtXvidIcon.Text = My.Settings.XvidPath
            txtDivxIcon.Text = My.Settings.DvixPath
            chkUseOriginal.Checked = My.Settings.UseOriginal
            chkUseCache.Checked = My.Settings.UseCache
            chkExportCoverImage.Checked = My.Settings.ExportCover
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    'TODO: Folder Name Parsing?
    Private Function generateImage(ByVal bmpCover As Bitmap, ByVal bmpBackdrop As Bitmap, ByVal sTitle As String, ByVal sSummary As String, ByVal sRuntime As String, ByVal sRating As String) As Bitmap
        Dim newbitmap As New Bitmap(1280, 720, Imaging.PixelFormat.Format32bppArgb)
        Dim g As Graphics
        Dim rectImage As New Rectangle(0, 0, 1280, 720)
        Dim rectCover As New Rectangle(50, 150, 240, 360)
        Dim rectAudio As New Rectangle(1162, 602, 113, 87)
        Dim rectVideo As New Rectangle(1044, 602, 113, 87)
        Dim rectTitle As New Rectangle(0, 100, 1280, 100)
        ' Dim rectTitleFrame As New Rectangle(0, 5, 1280, 150)
        Dim rectSummary As New Rectangle(405, 205, 745, 400)
        ' Dim rectMainText As New Rectangle(400, 150, 750, 450)
        Dim rectMainText As New Rectangle(0, 50, 1280, 720)
        
        Dim fTitle As New Font("Ariel", 32, FontStyle.Regular, GraphicsUnit.Point)
        Dim fSynopsis As New Font("Ariel", 18, FontStyle.Regular, GraphicsUnit.Point)
        Dim fRunTime As New Font("Ariel", 15, FontStyle.Bold, GraphicsUnit.Point)
        Dim sfTitle = New StringFormat
        Dim sfSynopsis As New StringFormat

        Try
            sfSynopsis.Alignment = StringAlignment.Near
            sfSynopsis.LineAlignment = StringAlignment.Near
            sfTitle.Alignment = StringAlignment.Center
            sfTitle.LineAlignment = StringAlignment.Center
            g = Graphics.FromImage(newbitmap)
            g.Clear(Color.White)
            g.SmoothingMode = Drawing2D.SmoothingMode.HighQuality
            g.TextRenderingHint = Drawing.Text.TextRenderingHint.AntiAliasGridFit
            g.DrawImage(bmpBackdrop, rectImage)

            ' g.DrawImage(My.Resources.Images.TitleBG, rectTitleFrame)
            g.DrawImage(My.Resources.Images.shade, rectMainText)
            If My.Settings.IncludeCover Then
                g.DrawImage(bmpCover, rectCover)
            End If

            If My.Settings.IncludeTitle Then
                g.DrawString(sTitle, fTitle, Brushes.White, rectTitle, sfTitle)
            End If
            If My.Settings.IncludeSummary Then
                g.DrawString(sSummary, fSynopsis, Brushes.White, rectSummary, sfSynopsis)
            End If
            If My.Settings.IncludeRuntime Then
                g.DrawImage(My.Resources.Images.clock, 425, 450)
                g.DrawString(sRuntime, fRunTime, Brushes.White, 490, 475)
            End If
            If My.Settings.IncludeRating Then
                g.DrawImage(My.Resources.Images.favorite, 925, 450)
                g.DrawString(sRating, fRunTime, Brushes.White, 1000, 475)
            End If
            If bmpAudioFormat IsNot Nothing Then
                g.DrawImage(bmpAudioFormat, rectAudio)
            End If
            If bmpVideoResolution IsNot Nothing Then
                g.DrawImage(bmpVideoResolution, rectVideo)
            End If
            createdImage = newbitmap
            createdCover = bmpCover
            Return newbitmap
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Function
    Private Function searchForMovie(ByVal sMovieName As String) As Integer

        Dim httpReq As HttpWebRequest
        Dim httpResponse As HttpWebResponse
        Try
            Dim sStrippedTitle = stripMovieName(sMovieName)
            If sStrippedTitle <> "" Then
                sMovieName = sStrippedTitle
            End If
            LogManual("Getting Movie " & sStrippedTitle)
            httpReq = WebRequest.Create(String.Format(My.Settings.MovieDBSearchURL, API_KEY, sMovieName))
            httpResponse = httpReq.GetResponse

            Dim stream = httpResponse.GetResponseStream

            Dim doc As New XDocument
            Dim reader As New XmlTextReader(stream)
            doc = XDocument.Load(reader)
            Dim q = From c In doc.Elements("OpenSearchDescription").Elements("movies").Elements("movie") _
                    Select c
            Dim firstOBJ As Object = Nothing
            Dim bExactMatch As Boolean = False
            For Each obj In q
                If CStr(obj).IndexOf("Nothing found.") = -1 Then
                    ' firstOBJ = o
                    If LCase(obj.Element("name").Value).Equals(LCase(sMovieName)) Then
                        firstOBJ = obj
                        bExactMatch = True
                        Exit For
                    End If
                    If firstOBJ Is Nothing Then
                        'exact match not found so use first one retuned(closest match)
                        firstOBJ = q(0)
                        bExactMatch = False
                    End If
                Else
                    LogManual("Movie Not Found. Searching IMDB")
                    bNotFoundOnMovieDB = True
                    If TabControl1.SelectedIndex = 1 Then
                        'we know user is in batch mode 
                        searchIMDBBatch(sMovieName, 0)
                    Else
                        searchIMDB(sMovieName, 0)
                    End If
                End If
            Next
            If firstOBJ IsNot Nothing Then
                Log("Movie ID " & firstOBJ.Element("id").Value & " found. Exact Match=" & bExactMatch.ToString)
                Return firstOBJ.Element("id").Value
            Else
                Return 0
            End If

        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Function
    Private Function searchForMovieIMDBId(ByVal sMovieName As String) As String
        Dim httpReq As HttpWebRequest
        Dim httpResponse As HttpWebResponse
        Try
            Dim sStrippedTitle = stripMovieName(sMovieName)
            If sStrippedTitle <> "" Then
                sMovieName = sStrippedTitle
            End If
            LogManual("Getting Movie " & sStrippedTitle)
            httpReq = WebRequest.Create(String.Format(My.Settings.MovieDBSearchURL, API_KEY, sMovieName))
            httpResponse = httpReq.GetResponse
            Log("Requesting Search Response")
            Dim stream = httpResponse.GetResponseStream
            Log("Response Received")
            Dim doc As New XDocument
            Dim reader As New XmlTextReader(stream)
            doc = XDocument.Load(reader)
            Dim q = From c In doc.Elements("OpenSearchDescription").Elements("movies").Elements("movie") _
                    Select c
            Dim firstOBJ As Object = Nothing
            Dim bExactMatch As Boolean = False
            For Each obj In q
                If CStr(obj).IndexOf("Nothing found.") = -1 Then
                    ' firstOBJ = o
                    If LCase(obj.Element("name").Value).Equals(LCase(sMovieName)) Then
                        firstOBJ = obj
                        bExactMatch = True
                        Exit For
                    End If
                    If firstOBJ Is Nothing Then
                        'exact match not found so use first one retuned(closest match)
                        firstOBJ = q(0)
                        bExactMatch = False
                    End If
                Else
                    Log("Movie Not Found")
                End If
            Next
            If firstOBJ IsNot Nothing Then
                Log("Movie ID " & firstOBJ.Element("id").Value & " found. Exact Match=" & bExactMatch.ToString)
                Return firstOBJ.Element("imdb_id").Value
            Else
                Return 0
            End If

        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Function
    Private Function getMovieInfo(ByVal id As Int16)
        Dim httpReq As HttpWebRequest
        Dim httpResponse As HttpWebResponse
        Try

            httpReq = WebRequest.Create(String.Format(My.Settings.MovieDBGetInfoUrl, API_KEY, id.ToString))
            Log("Getting Movie Info")
            httpResponse = httpReq.GetResponse
            Dim stream = httpResponse.GetResponseStream
            Log("Movie Info Received")
            Dim doc As New XDocument
            Dim reader As New XmlTextReader(stream)
            doc = XDocument.Load(reader)

            Dim q = From c In doc.Elements("OpenSearchDescription").Elements("movies").Elements("movie") _
                    Select c
            Dim firstOBJ = q.ElementAt(0)
            Dim sTitle As String = firstOBJ.Element("name").Value
            Dim sSummary As String = firstOBJ.Element("overview").Value
            Dim sRating As String = Math.Round(CDbl(firstOBJ.Element("rating").Value), 2).ToString
            Dim sRunTime As String = firstOBJ.Element("runtime").Value
            Dim q1 = From c1 In q.Elements("images").Elements("image") _
                   Where c1.Attribute("type") = "backdrop" _
                   Select c1
            Dim q2 = From c1 In q.Elements("images").Elements("image") _
                  Where c1.Attribute("type") = "poster" _
                  Select c1
            Log("Getting Backdrop")
            httpReq = WebRequest.Create(q1(0).Attribute("url").Value)
            httpResponse = httpReq.GetResponse
            Dim bmpBackdrop As New Bitmap(httpResponse.GetResponseStream)
            Log("Getting Poster")
            httpReq = WebRequest.Create(q2(0).Attribute("url").Value)
            httpResponse = httpReq.GetResponse
            Dim bmpCover As New Bitmap(httpResponse.GetResponseStream)
            Log("Generating Image")
            generateImage(bmpCover, bmpBackdrop, sTitle, sSummary, sRunTime, sRating)
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Function
    'called when in batch mode
    Private Function getMovieInfoIMDB(ByVal title As IMDbTitle)
        Dim httpReq As HttpWebRequest
        Dim httpResponse As HttpWebResponse
        Try
            currentTitle = title
            httpReq = WebRequest.Create(String.Format(My.Settings.MovieDBIMDBLookup, API_KEY, title.ID))
            Log("Getting Movie Info")
            httpResponse = httpReq.GetResponse
            Dim stream = httpResponse.GetResponseStream
            Log("Movie Info Received")
            Dim doc As New XDocument
            Dim reader As New XmlTextReader(stream)
            doc = XDocument.Load(reader)

            Dim q = From c In doc.Elements("OpenSearchDescription").Elements("movies").Elements("movie") _
                    Select c

            Dim firstOBJ = q.ElementAt(0)
            If CStr(firstOBJ).IndexOf("Nothing found") <> -1 Then
                firstOBJ = Nothing
            End If
            If firstOBJ IsNot Nothing Then
                Dim iMovieDBId = firstOBJ.Element("id").Value
                httpReq = WebRequest.Create(String.Format(My.Settings.MovieDBGetInfoUrl, API_KEY, iMovieDBId))
                httpResponse = httpReq.GetResponse
                stream = httpResponse.GetResponseStream
                reader = New XmlTextReader(stream)
                doc = XDocument.Load(reader)
                currentDoc = doc
                q = From c In doc.Elements("OpenSearchDescription").Elements("movies").Elements("movie") _
                        Select c
                firstOBJ = q.ElementAt(0)
            End If
            txtTitle.Text = title.Title
            'sometimes the imdb plot summarys have a trailing '|'. The following line removes it.
            txtSummary.Text = title.Plot.Replace("|", "")
            txtRating.Text = title.Rating
            txtRunTime.Text = title.Runtime
            Dim bmpBackdrop As Bitmap
            Dim bmpCover As Bitmap
            Dim bSkipMovie As Boolean = False


            'use imdbInfo
            If currentTitle.Title <> vbNullString Then
                ' apostrophies come back wierd. this line boxes that off.
                currentTitle.Title = currentTitle.Title.Replace("&#x27;", "'")
                txtTitle.Text = currentTitle.Title
            ElseIf firstOBJ IsNot Nothing Then
                txtTitle.Text = firstOBJ.Element("name").Value
            End If
            If currentTitle.Plot <> vbNullString Then
                txtSummary.Text = currentTitle.Plot.Replace("|", "")
            ElseIf firstOBJ IsNot Nothing Then
                txtSummary.Text = firstOBJ.Element("overview").Value
            End If
            If currentTitle.Rating <> vbNullString Then
                txtRating.Text = currentTitle.Rating
            ElseIf firstOBJ IsNot Nothing Then
                txtRating.Text = Math.Round(CDbl(firstOBJ.Element("rating").Value), 2).ToString
            End If
            If currentTitle.Runtime <> vbNullString Then
                txtRunTime.Text = currentTitle.Runtime
            ElseIf firstOBJ IsNot Nothing Then
                txtRunTime.Text = firstOBJ.Element("runtime").Value
            End If

            If currentTitle.Actors IsNot Nothing Then
                For Each actor In currentTitle.Actors
                    txtActors.Text = txtActors.Text & actor.Name & ", "
                Next
            Else
                Dim qActor = From c1 In q.Elements("cast").Elements("person") _
                             Where c1.Attribute("job") = "Actor" _
                             Select c1
                For Each actor In qActor
                    txtDirectors.Text = txtDirectors.Text & actor.Attribute("name").Value
                Next
            End If
            If currentTitle.Genres IsNot Nothing Then
                For Each genre In currentTitle.Genres
                    txtGenres.Text = txtGenres.Text & genre & ", "
                Next
                'genre support in MovieDB.org getInfo call?
            End If
            If currentTitle.Directors IsNot Nothing Then
                For Each director In currentTitle.Directors
                    txtDirectors.Text = txtDirectors.Text & director.Name & ", "
                Next
            Else
                Dim qDirector = From c1 In q.Elements("cast").Elements("person") _
             Where c1.Attribute("job") = "Director" _
             Select c1
                For Each director In qDirector
                    txtDirectors.Text = txtDirectors.Text & director.Attribute("name").Value
                Next
            End If
            If currentTitle.Year <> vbNullString Then
                txtYear.Text = currentTitle.Year
            End If

            Dim q1 = From c1 In q.Elements("images").Elements("image") _
                   Where c1.Attribute("type") = "backdrop" _
                   Select c1
            Dim q2 = From c1 In q.Elements("images").Elements("image") _
                  Where c1.Attribute("type") = "poster" _
                  Select c1
            If q1.Count = 0 Then
                If My.Settings.DefaultBackdrop <> vbNullString Then
                    Log("No Backdrops available from theMovieDB.org. Using Default.")
                    bmpBackdrop = New Bitmap(My.Settings.DefaultBackdrop)
                Else
                    Log("No Backdrops available from theMovieDB.org. No Default setup so skipping movie.")
                    bSkipMovie = True
                End If
            Else
                Log("Getting Backdrop")
                httpReq = WebRequest.Create(q1(0).Attribute("url").Value)
                httpResponse = httpReq.GetResponse
                bmpBackdrop = New Bitmap(httpResponse.GetResponseStream)

                If iFanartCount > 0 Then

                    Dim qFanArt = From c1 In q.Elements("images").Elements("image") _
                           Where c1.Attribute("type") = "backdrop" _
                           And c1.Attribute("size") = "poster" _
                           And c1.Attribute("url").Value.Replace("_poster", "") <> q1(0).Attribute("url").Value _
                           Select c1
                    For i As Integer = 0 To iFanartCount Step 1
                        If qFanArt.Count > i Then
                            Log("Getting Fanart " & (i + 1).ToString)
                            httpReq = WebRequest.Create(qFanArt(i).Attribute("url").Value)
                            httpResponse = httpReq.GetResponse
                            Select Case i
                                Case 0
                                    bmpFanArt1 = New Bitmap(httpResponse.GetResponseStream)
                                Case 1
                                    bmpFanArt2 = New Bitmap(httpResponse.GetResponseStream)
                                Case 2
                                    bmpFanArt3 = New Bitmap(httpResponse.GetResponseStream)
                            End Select

                        End If

                    Next
                End If
                End If
                If q2.Count = 0 Then
                    If title.CoverURL <> vbNullString Then
                        Log("No Poster available on theMovieDB.org for this movie. Attempting to get IMDB Poster")
                        httpReq = WebRequest.Create(title.CoverURL)
                        httpResponse = httpReq.GetResponse
                        createdCover = New Bitmap(httpResponse.GetResponseStream)
                    Else
                        Log("No Posters available on either IMDB or theMovieDB.org.Skipping Movie")
                        bSkipMovie = True
                    End If


                Else
                    Log("Getting Poster")
                    httpReq = WebRequest.Create(q2(0).Attribute("url").Value)
                    httpResponse = httpReq.GetResponse
                    createdCover = New Bitmap(httpResponse.GetResponseStream)
                End If
                If bSkipMovie = False Then
                    If My.Settings.AnalyseMKVs Then
                        'get MKV file name
                        Dim direcInfo As New IO.DirectoryInfo(currentBatchDirec)
                        Dim targetFile As String = ""
                    Dim fileAry As New List(Of IO.FileInfo)
                    fileAry.AddRange(direcInfo.GetFiles("*.mkv"))
                    fileAry.AddRange(direcInfo.GetFiles("*.avi"))
                    fileAry.AddRange(direcInfo.GetFiles("*.iso"))
                    fileAry.AddRange(direcInfo.GetFiles("*.vob"))
                        Dim maxSize As Long = 0
                        For Each f In fileAry
                            If f.Length > maxSize Then
                                targetFile = f.FullName
                            End If
                    Next
                    If targetFile <> vbNullString Then
                        getVideoInfo(targetFile)
                    End If
                End If
                Log("Generating Image")
                bmpBatchBackdrop = bmpBackdrop
                If chkUseOriginal.Checked = False Then
                    createdImage = ApplyTemplate(sDefaultTemplatePath, bmpBackdrop, createdCover)
                Else
                    createdImage = generateImage(createdCover, bmpBackdrop, txtTitle.Text, txtSummary.Text, txtRunTime.Text, txtRating.Text)
                End If
            End If
            'successfull so reset retry counter.
            iRetryCount = 0
        Catch wex As Net.WebException
            If iRetryCount <= 10 Then
                iRetryCount += 1
                Log(wex.Message & vbCrLf & "Retrying " & iRetryCount.ToString & " of 10.")
                getMovieInfoIMDB(title)
            Else
                Log(wex.Message & vbCrLf & " I have tried 10 times to get this movie and it isnt happening. Sorry :(")
                iRetryCount = 0
            End If
        Catch ex As Exception
            Log(ex.Message)
        End Try
    End Function
    Private Function stripMovieName(ByVal sMovieName As String) As String
        Dim sStrippedTitle As String = ""
        Dim iStartIndex As Integer = 0
        Dim iEndIndex As Integer = 0
        Dim iLength As Integer = 0
        Try
            'strip the movie year fro mthe title so themoviedb.org api will read it ok
            'year is in the format (yyyy)

            iStartIndex = sMovieName.IndexOf("(")
            If iStartIndex <> -1 Then
                'this title contains a year 
                iEndIndex = sMovieName.IndexOf(")")
                iLength = iEndIndex - iStartIndex
                sStrippedTitle = sMovieName.Remove(iStartIndex, iLength + 1)
            End If
            Return sStrippedTitle
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Function
    Private Sub Log(ByVal sMsg As String)
        Try
            txtStatus.AppendText(sMsg & vbCrLf)
            Application.DoEvents()
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub


    Private Sub btnProcess_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnProcess.Click
        'now enum thru the folder getting movie info for each one and placing folder & wd_tv jpgs in the folders
        lblStatus.Text = ""
        Dim bFreshDownload = False
        iFanartCount = 0

        Try
            Cursor.Current = Cursors.WaitCursor
            If txtBatchProcess.Text <> vbNullString Then
                Dim directoryList As String() ' array for directories
                directoryList = direcListBatch
                'check for number of fanart images in loaded template
                Dim doc As New XDocument
                Dim fs As New IO.FileStream(sDefaultTemplatePath, IO.FileMode.Open)
                Dim reader As New XmlTextReader(fs)
                doc = XDocument.Load(reader)
                Dim imageElements = From c In doc.Elements("Template").Elements("ImageDrawTemplate").Elements("Elements").Elements("ImageElement") _
                             Select c
              
                fs.Close()
                For Each img In imageElements
                    If img.Attribute("SourceData").Value.IndexOf("FANART") <> -1 Or img.Attribute("SourceData").Value.IndexOf("thumb1") <> -1 Or img.Attribute("SourceData").Value.IndexOf("thumb2") <> -1 Then
                        iFanartCount += 1
                    End If
                Next
                Log("The default template uses " & iFanartCount.ToString & " fanart\thumb images.")
                Dim iCount As Integer = 1
                For Each direc In directoryList
                    'House keeping*********
                    clearFanArt()
                    bNotFoundOnIMDB = False
                    bNotFoundOnMovieDB = False
                    createdCover = Nothing
                    createdImage = Nothing
                    bFreshDownload = False
                    bmpVideoResolution = Nothing
                    bmpAudioFormat = Nothing
                    clearMovieInfo()
                    '***********************
                    lblStatus.Text = "Processing " & iCount.ToString & " of " & directoryList.Length.ToString & " movies."
                    Application.DoEvents()
                    Dim movieName = direc.Remove(0, txtBatchProcess.Text.Count + 1)
                    sCurrentBatchMovie = movieName
                    currentBatchDirec = direc
                    If IO.File.Exists(direc & "\Movie_Info.xml") And My.Settings.UseCache Then
                        LoadXML(direc & "\Movie_Info.xml")
                        createdCover = New Bitmap(direc & "\cover.jpg")
                        If iFanartCount > 0 Then
                            If IO.File.Exists(direc & "\fanart1.jpg") Then
                                bmpFanArt1 = New Bitmap(direc & "\fanart1.jpg")
                            End If
                            If IO.File.Exists(direc & "\fanart2.jpg") Then
                                bmpFanArt2 = New Bitmap(direc & "\fanart2.jpg")
                            End If
                            If IO.File.Exists(direc & "\fanart3.jpg") Then
                                bmpFanArt3 = New Bitmap(direc & "\fanart3.jpg")
                            End If
                        End If
                        If My.Settings.AnalyseMKVs Then
                            'get MKV file name
                            Dim direcInfo As New IO.DirectoryInfo(currentBatchDirec)
                            Dim targetFile As String = ""

                            Dim fileAry As New List(Of IO.FileInfo)
                            fileAry.AddRange(direcInfo.GetFiles("*.mkv"))
                            fileAry.AddRange(direcInfo.GetFiles("*.avi"))
                            fileAry.AddRange(direcInfo.GetFiles("*.iso"))
                            fileAry.AddRange(direcInfo.GetFiles("*.vob"))
                            Dim maxSize As Long = 0
                            For Each f In fileAry
                                If f.Length > maxSize Then
                                    targetFile = f.FullName
                                End If
                            Next
                            If targetFile <> vbNullString Then
                                getVideoInfo(targetFile)
                            End If
                        End If
                        createdImage = ApplyTemplate(sDefaultTemplatePath, New Bitmap(direc & "\backdrop.jpg"), createdCover)
                        bFreshDownload = False

                    Else
                        searchIMDBBatch(movieName, 0)
                        bFreshDownload = True
                    End If


                    If createdCover IsNot Nothing Then
                        If My.Settings.ExportCover Then
                            Dim bmpFolderImage As New Bitmap(My.Settings.CoverWidth, My.Settings.CoverHeight)

                            Dim g = Graphics.FromImage(bmpFolderImage)
                            Dim coverRect As New Rectangle(0, 0, My.Settings.CoverWidth, My.Settings.CoverHeight)

                            g.DrawImage(createdCover, coverRect)
                            bmpFolderImage.Save(direc & "\" & My.Settings.CoverName, Imaging.ImageFormat.Jpeg)
                        End If
                    End If
                    If createdImage IsNot Nothing Then
                        If My.Settings.UseCache And bFreshDownload Then

                            GenerateXML(direc)
                            bmpBatchBackdrop.Save(direc & "\backdrop.jpg", Imaging.ImageFormat.Jpeg)
                            createdCover.Save(direc & "\cover.jpg", Imaging.ImageFormat.Jpeg)
                            If bmpFanArt1 IsNot Nothing Then
                                bmpFanArt1.Save(direc & "\fanart1.jpg")
                            End If
                            If bmpFanArt2 IsNot Nothing Then
                                bmpFanArt2.Save(direc & "\fanart2.jpg")
                            End If
                            If bmpFanArt3 IsNot Nothing Then
                                bmpFanArt3.Save(direc & "\fanart3.jpg")
                            End If
                        End If
                        createdImage.Save(direc & "\" & My.Settings.MovieSheetName, Imaging.ImageFormat.Jpeg)
                        'populate previewbox
                        pbGeneratedImage.ImageLocation = direc & "\" & My.Settings.MovieSheetName
                        pbGeneratedImage.SizeMode = PictureBoxSizeMode.StretchImage
                        Application.DoEvents()
                    End If
                    'End If

                    iCount += 1
                Next
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally
            Cursor.Current = Cursors.Default
        End Try
    End Sub

    Private Sub txtManualFolderSelection_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtManualFolderSelection.Enter
        Dim thFolderSelection As New Thread(New ThreadStart(AddressOf FolderBrowserDialog1.ShowDialog))
        thFolderSelection.SetApartmentState(ApartmentState.STA)
        thFolderSelection.IsBackground = True
        thFolderSelection.Start()
        thFolderSelection.Join()
        'thFolderSelection.
        ' If FolderBrowserDialog1.ShowDialog(Me) = 1 Then
        If FolderBrowserDialog1.SelectedPath <> vbNullString Then
            txtManualFolderSelection.Text = FolderBrowserDialog1.SelectedPath
            populateMovieList()
            My.Settings.DefaultFolder = txtManualFolderSelection.Text
            My.Settings.Save()
            FileSystemWatcher1.Path = My.Settings.DefaultFolder
        End If
        ' End If
    End Sub
    Private Sub populateMovieList()
        lstMovies.SelectionMode = SelectionMode.None
        Dim directoryList As String() ' array for directories
        If chkUnprocessedOnlyManual.Checked Then
            directoryList = hideProcessedFolders(IO.Directory.GetDirectories(txtManualFolderSelection.Text))
        Else
            directoryList = IO.Directory.GetDirectories(txtManualFolderSelection.Text)
        End If
        direcList = directoryList
        Dim movieArray As New ArrayList
        Dim mvAry As New List(Of KeyValuePair(Of String, String))

        For Each direc In directoryList

            Dim movieName = direc.Remove(0, txtManualFolderSelection.Text.Count + 1)
            Dim s As New KeyValuePair(Of String, String)(direc, movieName)
            mvAry.Add(s)
        Next
        lstMovies.DataSource = mvAry
        lstMovies.DisplayMember = "Value"
        lstMovies.SelectionMode = SelectionMode.One
    End Sub
    Private Sub populateMovieListBatch()
        lstMoviesBatch.SelectionMode = SelectionMode.None
        Dim directoryList As String() ' array for directories
        If chkUnprocessedOnly.Checked Then
            directoryList = hideProcessedFolders(IO.Directory.GetDirectories(txtBatchProcess.Text))
        Else
            directoryList = IO.Directory.GetDirectories(txtBatchProcess.Text)
        End If
        direcListBatch = directoryList
        Dim movieArray As New ArrayList
        Dim mvAry As New List(Of KeyValuePair(Of String, String))

        For Each direc In directoryList
            Dim movieName = direc.Remove(0, txtBatchProcess.Text.Count + 1)
            Dim s As New KeyValuePair(Of String, String)(direc, movieName)
            mvAry.Add(s)
        Next
        lstMoviesBatch.DataSource = mvAry
        lstMoviesBatch.DisplayMember = "Value"
        '  lstMovies.SelectionMode = SelectionMode.One
    End Sub

    Private Function hideProcessedFolders(ByVal direcList() As String) As String()
        Dim currentDirec As IO.Directory
        Dim sRetObj As New List(Of String)

        Try
            For Each direc In direcList
                Dim files = IO.Directory.GetFiles(direc)
                Dim bFound As Boolean = False
                For Each f In files
                    If f.Equals(direc & "\" & My.Settings.MovieSheetName) = True Then
                        bFound = True
                    End If
                Next
                If bFound = False Then
                    sRetObj.Add(direc)
                End If
            Next
            Return sRetObj.ToArray
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Function

    Private Sub lstMovies_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles lstMovies.SelectedIndexChanged
        Try
            Dim loadedBitmap As Bitmap
            Dim s As KeyValuePair(Of String, String)
            s = lstMovies.SelectedItem
            'first check and show any existing moviesheet
            Dim direcInfo As New IO.DirectoryInfo(s.Key)
            Dim files = direcInfo.GetFiles(My.Settings.MovieSheetName)
            bmpVideoResolution = Nothing
            bmpAudioFormat = Nothing
            If files.Length <> 0 Then
                txtManualLog.Clear()
                pnlMovieInfo.Visible = False
                btnEditMovieInfo.Text = "Edit Movie Info"
                pbExistingSheet.Size = New Size(960, 540)
                Dim file = files.First
                loadedBitmap = New Bitmap(file.FullName)
                pnlCreateSheet.Visible = False
                btnRedo.Visible = True
                pbExistingSheet.Image = loadedBitmap
                pbExistingSheet.Visible = True
                pbExistingSheet.SizeMode = PictureBoxSizeMode.StretchImage
                pnlApplyTemplate.Visible = True
                If IO.File.Exists(s.Key & "\Movie_Info.xml") = True Then
                    btnEditMovieInfo.Visible = True
                    LoadXML(s.Key & "\Movie_Info.xml")
                Else
                    btnEditMovieInfo.Visible = False
                End If
                Application.DoEvents()
            Else
                pnlApplyTemplate.Visible = False
                loadedBitmap = Nothing
                pbExistingSheet.Visible = False
                pnlCreateSheet.Visible = True
                btnRedo.Visible = False
                '*********bit of house keeping**********
                bNotFoundOnIMDB = False
                bNotFoundOnMovieDB = False
                txtManualLog.Text = ""
                lstBackdrops.Items.Clear()
                lstPoster.DataSource = Nothing
                pbBackdropPreview.Image = Nothing
                pbPosterPreview.Image = Nothing
                aryBackdrops.Clear()
                aryPosters.Clear()
                btnMoreFound.Visible = False
                Application.DoEvents()
                '**************************************
                Cursor.Current = Cursors.WaitCursor
                btnIncorrectFilm.Visible = True
                If My.Settings.PrimarySource = "MovieDB" Then
                    Dim movieID = searchForMovie(s.Value)
                    If movieID <> 0 Then
                        LogManual("Movie Found ID:" & movieID.ToString)
                        populateBackdrops(movieID)
                        populatePosters()
                        populateMovieInfo()
                        Application.DoEvents()
                        btnIncorrectFilm.Visible = True
                    Else
                        ' MessageBox.Show("Movie Not Found")
                        btnIncorrectFilm.Visible = True
                    End If
                Else
                    'use IMDB as primary source
                    searchIMDB(s.Value, 0)
                End If
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally
            Cursor.Current = Cursors.Default
        End Try
    End Sub
    Private Sub clearMovieInfo()
        txtTitle.Text = ""
        txtSummary.Text = ""
        txtRating.Text = ""
        txtRunTime.Text = ""
        txtActors.Text = ""
        txtGenres.Text = ""
        txtYear.Text = ""
        txtDirectors.Text = ""
    End Sub
    Private Sub populateMovieInfo()
        Try

            clearMovieInfo()
            Dim doc As New XDocument
            doc = currentDoc
            Dim q = From c In doc.Elements("OpenSearchDescription").Elements("movies").Elements("movie") _
                    Select c
            Dim firstOBJ = q.ElementAt(0)
            If CStr(firstOBJ).IndexOf("Nothing found") <> -1 Then
                firstOBJ = Nothing
            End If

            If My.Settings.PrimarySource = "MovieDB" And bNotFoundOnMovieDB = False Then

                txtTitle.Text = firstOBJ.Element("name").Value
                txtSummary.Text = firstOBJ.Element("overview").Value
                txtRating.Text = Math.Round(CDbl(firstOBJ.Element("rating").Value), 2).ToString
                txtRunTime.Text = firstOBJ.Element("runtime").Value
            Else
                'use imdbInfo
                If currentTitle.Title <> vbNullString Then
                    ' apostrophies come back wierd. this line boxes that off.
                    currentTitle.Title = currentTitle.Title.Replace("&#x27;", "'")
                    txtTitle.Text = currentTitle.Title
                ElseIf firstOBJ IsNot Nothing Then
                    txtTitle.Text = firstOBJ.Element("name").Value
                End If
                If currentTitle.Plot <> vbNullString Then
                    txtSummary.Text = currentTitle.Plot.Replace("|", "")
                ElseIf firstOBJ IsNot Nothing Then
                    txtSummary.Text = firstOBJ.Element("overview").Value
                End If
                If currentTitle.Rating <> vbNullString Then
                    txtRating.Text = currentTitle.Rating
                ElseIf firstOBJ IsNot Nothing Then
                    txtRating.Text = Math.Round(CDbl(firstOBJ.Element("rating").Value), 2).ToString
                End If
                If currentTitle.Runtime <> vbNullString Then
                    txtRunTime.Text = currentTitle.Runtime
                ElseIf firstOBJ IsNot Nothing Then
                    txtRunTime.Text = firstOBJ.Element("runtime").Value
                End If

                If currentTitle.Actors IsNot Nothing Then
                    For Each actor In currentTitle.Actors
                        txtActors.Text = txtActors.Text & actor.Name & ", "
                    Next
                Else
                    Dim q1 = From c1 In q.Elements("cast").Elements("person") _
                Where c1.Attribute("job") = "Actor" _
                Select c1
                    For Each actor In q1
                        txtDirectors.Text = txtDirectors.Text & actor.Attribute("name").Value
                    Next
                End If
                If currentTitle.Genres IsNot Nothing Then
                    For Each genre In currentTitle.Genres
                        txtGenres.Text = txtGenres.Text & genre & ", "
                    Next
                    'genre support in MovieDB.org getInfo call?
                End If
                If currentTitle.Directors IsNot Nothing Then
                    For Each director In currentTitle.Directors
                        txtDirectors.Text = txtDirectors.Text & director.Name & ", "
                    Next
                Else
                    Dim q1 = From c1 In q.Elements("cast").Elements("person") _
                 Where c1.Attribute("job") = "Director" _
                 Select c1
                    For Each director In q1
                        txtDirectors.Text = txtDirectors.Text & director.Attribute("name").Value
                    Next
                End If
                If currentTitle.Year <> vbNullString Then
                    txtYear.Text = currentTitle.Year
                End If
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub
    Private Sub populateBackdropsIMDB(ByVal imdbID As String)
        Dim httpReq As HttpWebRequest
        Dim httpResponse As HttpWebResponse
        Try
            Cursor.Current = Cursors.WaitCursor
            httpReq = WebRequest.Create(String.Format(My.Settings.MovieDBIMDBLookup, API_KEY, imdbID))
            httpResponse = httpReq.GetResponse
            Dim stream = httpResponse.GetResponseStream
            Dim doc As New XDocument
            Dim reader As New XmlTextReader(stream)
            doc = XDocument.Load(reader)
            currentDoc = doc
            Dim q = From c In doc.Elements("OpenSearchDescription").Elements("movies").Elements("movie") _
                    Select c
            Dim firstOBJ = q.ElementAt(0)
            'getInfo from movieDB.org to include cast
            Dim iMovieDBId = firstOBJ.Element("id").Value
            httpReq = WebRequest.Create(String.Format(My.Settings.MovieDBGetInfoUrl, API_KEY, iMovieDBId))
            httpResponse = httpReq.GetResponse
            stream = httpResponse.GetResponseStream
            reader = New XmlTextReader(stream)
            doc = XDocument.Load(reader)
            currentDoc = doc

            Dim q1 = From c1 In q.Elements("images").Elements("image") _
                   Where c1.Attribute("type") = "backdrop" And c1.Attribute("size") = "poster" _
                   Select c1
            If q1.Count = 0 Then
                logMultiThread("No Backdrops Available for this Movie.")
                'load default backdrop
                If My.Settings.DefaultBackdrop <> vbNullString Then
                    Dim bmp As New Bitmap(My.Settings.DefaultBackdrop)
                    Dim newBAckdrop = New KeyValuePair(Of Bitmap, String)(bmp, "SelectedBackdrop")
                    aryBackdrops.Add(newBAckdrop)
                    'lstBackdrops.DataSource = Nothing
                    'lstBackdrops.DataSource = aryBackdrops
                    'lstBackdrops.DisplayMember = "Value"
                    populateBackdropsList()
                End If
            Else
                logMultiThread("There are " & q1.Count.ToString & " backdrops available for this movie")
                aryBackdrops.Clear()
                'Dim aryBAckdrops As New List(Of KeyValuePair(Of Bitmap, String))
                Dim iCount As Integer = 0
                ReDim resetEvents(q1.Count - 1)

                For Each backdrop In q1
                    Dim params(1) As String
                    params(0) = backdrop.Attribute("url").Value
                    params(1) = iCount.ToString

                    ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf GetBackdrop), params)
                    resetEvents(iCount) = New ManualResetEvent(False)
                  
                    iCount += 1
                Next
                WaitHandle.WaitAll(resetEvents)
                populateBackdropsList()
                'lstBackdrops.DataSource = Nothing
                'lstBackdrops.DataSource = aryBackdrops
                'lstBackdrops.DisplayMember = "Value"

                logMultiThread("Backdrops downloaded")
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub
    Private Sub populateBackdropsList()
        Try
            lstBackdrops.Items.Clear()
            clearFanArt()
            For Each ary In aryBackdrops
                Dim lvi As New ListViewItem
                lvi.Text = ary.Value
                Dim s As New KeyValuePair(Of Bitmap, String)(ary.Key, ary.Value)
                lvi.Tag = s
                lstBackdrops.Items.Add(lvi)
            Next
            lstBackdrops.Items(0).Selected = True
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub
    Private Sub clearFanArt()
        mnuFanArt1.Checked = False
        mnuFanArt2.Checked = False
        mnuFanArt3.Checked = False
        bmpFanArt1 = Nothing
        bmpFanArt2 = Nothing
        bmpFanArt3 = Nothing
    End Sub

    Private Sub populateBackdrops(ByVal movieID As Integer)
        Dim httpReq As HttpWebRequest
        Dim httpResponse As HttpWebResponse
        Try
            Cursor.Current = Cursors.WaitCursor
            httpReq = WebRequest.Create(String.Format(My.Settings.MovieDBGetInfoUrl, API_KEY, movieID.ToString))
            logMultiThread("Movie Info")
            httpResponse = httpReq.GetResponse
            Dim stream = httpResponse.GetResponseStream
            logMultiThread("Movie Info Received")
            Dim doc As New XDocument
            Dim reader As New XmlTextReader(stream)
            doc = XDocument.Load(reader)
            currentDoc = doc
            Dim q = From c In doc.Elements("OpenSearchDescription").Elements("movies").Elements("movie") _
                    Select c
            Dim firstOBJ = q.ElementAt(0)

            Dim q1 = From c1 In q.Elements("images").Elements("image") _
                   Where c1.Attribute("type") = "backdrop" And c1.Attribute("size") = "poster" _
                   Select c1
            logMultiThread("There are " & q1.Count.ToString & " backdrops available for this movie")
            aryBackdrops.Clear()
            'Dim aryBAckdrops As New List(Of KeyValuePair(Of Bitmap, String))
            Dim iCount As Integer = 0
            ReDim resetEvents(q1.Count - 1)

            For Each backdrop In q1
                Dim params(1) As String
                params(0) = backdrop.Attribute("url").Value
                params(1) = iCount.ToString

                ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf GetBackdrop), params)
                resetEvents(iCount) = New ManualResetEvent(False)
                'Dim httpReq1 As HttpWebRequest
                'Dim httpResponse1 As HttpWebResponse
                'httpReq1 = WebRequest.Create(backdrop.Attribute("url").Value)
                'httpResponse1 = httpReq1.GetResponse
                'Dim bmpBackdrop As New Bitmap(httpResponse1.GetResponseStream)
                'Dim sImgName = backdrop.Attribute("url").Value.Replace(sImgUrl, "")
                'sImgName = sImgName.Replace("_poster", "")
                'Dim newBAckdrop = New KeyValuePair(Of Bitmap, String)(bmpBackdrop, sImgName)
                'aryBAckdrops.Add(newBAckdrop)
                iCount += 1
            Next
            WaitHandle.WaitAll(resetEvents)
            'lstBackdrops.DataSource = Nothing

            'lstBackdrops.DataSource = aryBackdrops
            'lstBackdrops.DisplayMember = "Value"
            populateBackdropsList()
            logMultiThread("Backdrops downloaded")
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally
            Cursor.Current = Cursors.Default
        End Try

    End Sub
    Private Sub populateBAckdropPreview(ByVal bmpbackdrop As Bitmap)

        pbBackdropPreview.Image = bmpbackdrop
        pbBackdropPreview.SizeMode = PictureBoxSizeMode.StretchImage
    End Sub
    Private Sub getIMDBPoster(ByVal sUrl As String)
        Try
            If sUrl <> vbNullString Then
                aryPosters.Clear()
                Dim httpReq1 As HttpWebRequest
                Dim httpResponse1 As HttpWebResponse
                httpReq1 = WebRequest.Create(sUrl)
                httpResponse1 = httpReq1.GetResponse
                Dim bmpPoster As New Bitmap(httpResponse1.GetResponseStream)

                Dim newPoster = New KeyValuePair(Of Bitmap, String)(bmpPoster, "IMDBPoster")
                aryPosters.Add(newPoster)
                Application.DoEvents()
                lstPoster.DataSource = Nothing
                lstPoster.DataSource = aryPosters
                lstPoster.DisplayMember = "Value"
                LogManual("IMDB Poster Downloaded")
            Else
                LogManual("No IMDB Poster Available.")
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub
    Private Sub populatePosters()
        Try
            Dim doc As New XDocument
            doc = currentDoc
            Dim q = From c In doc.Elements("OpenSearchDescription").Elements("movies").Elements("movie") _
                    Select c

            Dim q1 = From c1 In q.Elements("images").Elements("image") _
                   Where c1.Attribute("type") = "poster" And c1.Attribute("size") = "thumb" _
                   Select c1
            If q1.Count = 0 Then
                logMultiThread("There are no poster available on TheMoviedb.org for this movie. Attempting to get IMDB poster.")
                getIMDBPoster(currentTitle.CoverURL)
            Else
                LogManual("There are " & q1.Count.ToString & " posters available for this movie")
                aryPosters.Clear()
                Dim iCount As Integer = 0
                ReDim resetEventsPoster(q1.Count - 1)
                For Each poster In q1

                    Dim params(1) As String
                    params(0) = poster.Attribute("url").Value
                    params(1) = iCount.ToString
                    ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf GetPoster), params)
                    resetEventsPoster(iCount) = New ManualResetEvent(False)
                    'Dim httpReq1 As HttpWebRequest
                    'Dim httpResponse1 As HttpWebResponse
                    'httpReq1 = WebRequest.Create(poster.Attribute("url").Value)
                    'httpResponse1 = httpReq1.GetResponse
                    'Dim bmpPoster As New Bitmap(httpResponse1.GetResponseStream)
                    'Dim sImgName = poster.Attribute("url").Value.Replace(sImgUrlPoster, "")
                    'sImgName = sImgName.Replace("_thumb", "")
                    'Dim newPoster = New KeyValuePair(Of Bitmap, String)(bmpPoster, sImgName)
                    'aryPosters.Add(newPoster)
                    iCount += 1
                Next
                WaitHandle.WaitAll(resetEventsPoster)
                lstPoster.DataSource = Nothing
                lstPoster.DataSource = aryPosters
                lstPoster.DisplayMember = "Value"
                LogManual("Posters Downloaded")
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub
    Private Sub GetBackdrop(ByVal objIN As Object)
        Dim iCount = CInt(objIN(1))
        Try

            Dim url = CStr(objIN(0))

            ' logMultiThread("Getting backdrop " & url)
            Dim httpReq1 As HttpWebRequest
            Dim httpResponse1 As HttpWebResponse
            httpReq1 = WebRequest.Create(url)
            httpResponse1 = httpReq1.GetResponse
            Dim bmpBackdrop As New Bitmap(httpResponse1.GetResponseStream)
            ' Dim sImgID = backdrop.Attribute("id").Value
            ' Dim sUrlToRemove = String.Format(sImgUrl, sImgID)
            Dim sImgName = url.Replace(sImgUrl, "")
            sImgName = sImgName.Replace("_poster", "")
            Dim newBAckdrop = New KeyValuePair(Of Bitmap, String)(bmpBackdrop, sImgName)
            aryBackdrops.Add(newBAckdrop)
        Catch ex As Exception
        Finally
            resetEvents(iCount).Set()
        End Try
    End Sub
    Private Sub GetPoster(ByVal objIN As Object)
        Dim url = objIN(0)
        Dim iCount = objIN(1)
        Try
            Dim httpReq1 As HttpWebRequest
            Dim httpResponse1 As HttpWebResponse
            httpReq1 = WebRequest.Create(url)
            httpResponse1 = httpReq1.GetResponse
            Dim bmpPoster As New Bitmap(httpResponse1.GetResponseStream)
            Dim sImgName = url.Replace(sImgUrlPoster, "")
            sImgName = sImgName.Replace("_thumb", "")
            Dim newPoster = New KeyValuePair(Of Bitmap, String)(bmpPoster, sImgName)
            aryPosters.Add(newPoster)
        Catch ex As Exception
        Finally
            resetEventsPoster(iCount).Set()
        End Try
    End Sub
    Private Sub lstBackdrops_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles lstBackdrops.SelectedIndexChanged
        If lstBackdrops.SelectedItems.Count > 0 Then
            Dim s As New KeyValuePair(Of Bitmap, String)
            s = lstBackdrops.SelectedItems(0).Tag
            populateBAckdropPreview(s.Key)
        End If
      
    End Sub

    Private Sub lstPoster_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles lstPoster.SelectedIndexChanged
        Dim s As New KeyValuePair(Of Bitmap, String)
        s = lstPoster.SelectedItem
        pbPosterPreview.Image = s.Key
        pbPosterPreview.SizeMode = PictureBoxSizeMode.StretchImage
    End Sub

    Private Sub btnBackdropPreview_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBackdropPreview.Click
        Dim s As New KeyValuePair(Of Bitmap, String)
        s = lstBackdrops.SelectedItems(0).Tag

        PictureBox2.Image = getHDImage(s.Value, True)
        TabControl1.SelectedTab = TabPage4
    End Sub
    Private Function getHDImage(ByVal sValue As String, ByVal bIsBackdrop As Boolean) As Bitmap
        Try

        
            If sValue = "IMDBPoster" Or sValue = "SelectedBackdrop" Or sValue = "SelectedPoster" Then
                If bIsBackdrop Then
                    Dim s As New KeyValuePair(Of Bitmap, String)
                    s = lstBackdrops.SelectedItems(0).Tag
                    Return s.Key
                Else
                    Dim s As New KeyValuePair(Of Bitmap, String)
                    s = lstPoster.SelectedItem
                    Return s.Key
                End If
            Else
                Dim httpReq1 As HttpWebRequest
                Dim httpResponse1 As HttpWebResponse
                Dim sFileName = sValue
                If sFileName.IndexOf(".jpg") = -1 Then
                    sFileName = sFileName & ".jpg"
                End If
                If bIsBackdrop Then
                    httpReq1 = WebRequest.Create(sImgUrl & sFileName)
                Else
                    httpReq1 = WebRequest.Create(sImgUrlPoster & sFileName)
                End If

                httpResponse1 = httpReq1.GetResponse
                Dim bmpHDImage As New Bitmap(httpResponse1.GetResponseStream)
                Return bmpHDImage


            End If
        Catch ex As Exception
     
            MessageBox.Show("For some reason the selected " & IIf(bIsBackdrop, "Backdrop", "Poster") & " could not be found. Please select a different one and try again")

        End Try
    End Function
    Private Sub btnGenerate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGenerate.Click
        Try
            If sDefaultTemplatePath <> vbNullString And My.Settings.UseOriginal = False Then

                Cursor.Current = Cursors.WaitCursor
                Dim s As New KeyValuePair(Of String, String)
                Dim selectedBackdrop As New KeyValuePair(Of Bitmap, String)
                Dim selectedPoster As New KeyValuePair(Of Bitmap, String)
                selectedBackdrop = lstBackdrops.SelectedItems(0).Tag
                selectedPoster = lstPoster.SelectedItem
                s = lstMovies.SelectedItem
                'If bNotFoundOnMovieDB = False Then
                '    Dim doc As New XDocument
                '    doc = currentDoc

                '    Dim q = From c In doc.Elements("OpenSearchDescription").Elements("movies").Elements("movie") _
                '            Select c
                '    Dim firstOBJ = q.ElementAt(0)
                'End If
                If My.Settings.AnalyseMKVs Then
                    'get MKV file name
                    Dim direcInfo As New IO.DirectoryInfo(s.Key)
                    Dim targetFile As String = ""
                    Dim fileAry As New List(Of IO.FileInfo)
                    fileAry.AddRange(direcInfo.GetFiles("*.mkv"))
                    fileAry.AddRange(direcInfo.GetFiles("*.avi"))
                    fileAry.AddRange(direcInfo.GetFiles("*.wmv"))
                    fileAry.AddRange(direcInfo.GetFiles("*.vob"))
                    Dim maxSize As Long = 0
                    For Each f In fileAry
                        If f.Length > maxSize Then
                            targetFile = f.FullName
                        End If
                    Next
                    If targetFile <> vbNullString Then
                        getVideoInfo(targetFile)
                    End If

                End If
                Dim sTitle As String = txtTitle.Text
                Dim sSummary As String = txtSummary.Text
                Dim sRating As String = txtRating.Text.ToString
                Dim sRunTime As String = txtRunTime.Text.ToString
                Dim hdBackdrop = getHDImage(selectedBackdrop.Value, True)
                Dim hdposter As Bitmap
                Dim bmpFolderImage As New Bitmap(My.Settings.CoverWidth, My.Settings.CoverHeight)

                hdposter = getHDImage(selectedPoster.Value, False)
                Dim g = Graphics.FromImage(bmpFolderImage)
                Dim coverRect As New Rectangle(0, 0, My.Settings.CoverWidth, My.Settings.CoverHeight)

                g.DrawImage(hdposter, coverRect)
                If chkUseOriginal.Checked = False Then
                    createdImage = ApplyTemplate(sDefaultTemplatePath, hdBackdrop, hdposter)
                Else
                    createdImage = generateImage(hdposter, hdBackdrop, sTitle, sSummary, sRunTime, sRating)
                End If

                createdImage.Save(s.Key & "\" & My.Settings.MovieSheetName, Imaging.ImageFormat.Jpeg)

                If My.Settings.ExportCover Then
                    bmpFolderImage.Save(s.Key & "\" & My.Settings.CoverName, Imaging.ImageFormat.Jpeg)
                End If
                If My.Settings.UseCache Then
                    GenerateXML(s.Key)
                    hdBackdrop.Save(s.Key & "\backdrop.jpg", Imaging.ImageFormat.Jpeg)
                    hdposter.Save(s.Key & "\cover.jpg", Imaging.ImageFormat.Jpeg)
                    If bmpFanArt1 IsNot Nothing Then
                        bmpFanArt1.Save(s.Key & "\fanart1.jpg")
                    End If
                    If bmpFanArt2 IsNot Nothing Then
                        bmpFanArt2.Save(s.Key & "\fanart2.jpg")
                    End If
                    If bmpFanArt3 IsNot Nothing Then
                        bmpFanArt3.Save(s.Key & "\fanart3.jpg")
                    End If
                End If

                PictureBox1.Image = createdImage
                LogManual("Done")
            Else
                MessageBox.Show("There is no default template selected. Please select a default template from the settings tab.", "Hold on a sec...", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally
            Cursor.Current = Cursors.Default
        End Try
    End Sub
    Private Sub GenerateXML(ByVal path As String)
        Try
            Dim myXmlSettings As New XmlWriterSettings
            myXmlSettings.Indent = True
            myXmlSettings.NewLineOnAttributes = True

            Using ProductWriter As XmlWriter = XmlWriter.Create(path & "\Movie_Info.xml", myXmlSettings)

                ProductWriter.WriteComment("**bean_ian**WDTV Movie Generator**")
                ProductWriter.WriteStartElement("Movie")
                ProductWriter.WriteAttributeString("Title", txtTitle.Text)
                ProductWriter.WriteAttributeString("Plot", txtSummary.Text)
                ProductWriter.WriteAttributeString("Runtime", txtRunTime.Text)
                ProductWriter.WriteAttributeString("Rating", txtRating.Text)
                ProductWriter.WriteAttributeString("Year", txtYear.Text)

                ProductWriter.WriteAttributeString("Genres", txtGenres.Text)


                ProductWriter.WriteAttributeString("Actors", txtActors.Text)

                ProductWriter.WriteAttributeString("Directors", txtDirectors.Text)


                ProductWriter.WriteEndElement()

            End Using
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub
    Private Sub generateSilent(ByVal sDirectory As String, ByVal sMovieName As String)
        Try

            getMovieInfo(searchForMovie(sMovieName))
            'save output files
            createdCover.Save(sDirectory & "\" & My.Settings.CoverName, Imaging.ImageFormat.Jpeg)
            createdImage.Save(sDirectory & "\" & My.Settings.MovieSheetName, Imaging.ImageFormat.Jpeg)
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally
            Cursor.Current = Cursors.Default
        End Try
    End Sub
    Private Sub LogManual(ByVal sMsg As String)
        txtManualLog.AppendText(sMsg & vbCrLf)
        Application.DoEvents()
    End Sub
    Private Sub logMultiThread(ByVal sMsg As String)
        Me.Invoke(New UpdateTextHandler(AddressOf LogManual), sMsg)

    End Sub

    Private Sub btnGenerateNoText_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Try

            Cursor.Current = Cursors.WaitCursor
            Dim s As New KeyValuePair(Of String, String)
            Dim selectedBackdrop As New KeyValuePair(Of Bitmap, String)
            Dim selectedPoster As New KeyValuePair(Of Bitmap, String)
            selectedBackdrop = lstBackdrops.SelectedItems(0).Tag
            selectedPoster = lstPoster.SelectedItem
            s = lstMovies.SelectedItem
            Dim doc As New XDocument
            doc = currentDoc

            Dim q = From c In doc.Elements("OpenSearchDescription").Elements("movies").Elements("movie") _
                    Select c
            Dim firstOBJ = q.ElementAt(0)
            Dim sTitle As String = firstOBJ.Element("name").Value
            Dim sSummary As String = firstOBJ.Element("overview").Value
            Dim sRating As String = Math.Round(CDbl(firstOBJ.Element("rating").Value), 2).ToString
            Dim sRunTime As String = firstOBJ.Element("runtime").Value
            createdImage = generateImage(getHDImage(selectedPoster.Value, False), getHDImage(selectedBackdrop.Value, True), "", "", sRunTime, sRating)
            createdImage.Save(s.Key & "\wd_tv.jpg", Imaging.ImageFormat.Jpeg)
            createdCover = selectedPoster.Key
            createdCover.Save(s.Key & "\folder.jpg", Imaging.ImageFormat.Jpeg)
            PictureBox1.Image = createdImage
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally
            Cursor.Current = Cursors.Default
        End Try
    End Sub

    Private Sub btnSaveSetting_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSaveSetting.Click
        Try
            My.Settings.IncludeCover = chkIncludeCover.Checked
            My.Settings.IncludeRating = chkIncludeRating.Checked
            My.Settings.IncludeRuntime = chkIncludeRuntime.Checked
            My.Settings.IncludeSummary = chkIncludeSummary.Checked
            My.Settings.IncludeTitle = chkIncludeTitle.Checked
            My.Settings.DefaultBackdrop = txtDefaultBackdrop.Text
            My.Settings.CoverName = txtCoverName.Text
            My.Settings.MovieSheetName = txtMovieSheetName.Text
            My.Settings.CoverHeight = CInt(txtCoverHeight.Text)
            My.Settings.CoverWidth = CInt(txtCoverWidth.Text)
            My.Settings.UseCache = chkUseCache.Checked
            My.Settings.ExportCover = chkExportCoverImage.Checked
            If optIMDB.Checked Then
                My.Settings.PrimarySource = "IMDB"
            Else
                My.Settings.PrimarySource = "MovieDB"
            End If
            If optEnabled.Checked Then
                My.Settings.AnalyseMKVs = True
            Else
                My.Settings.AnalyseMKVs = False
            End If
            My.Settings.DolbyPath = txtDolbyDigital.Text
            My.Settings.DTSPath = txtDTS.Text
            My.Settings.p1080 = txt1080.Text
            My.Settings.p720 = txt720.Text
            My.Settings.DvixPath = txtDivxIcon.Text
            My.Settings.DVDPath = txtDVDIcon.Text
            My.Settings.XvidPath = txtXvidIcon.Text
            My.Settings.Save()
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub btnGo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGo.Click
        Try
            txtStatus.Clear()
            Log("Override Used, searching for " & txtOverride.Text)
            If My.Settings.PrimarySource = "MovieDB" Then
                Dim movieID = searchForMovie(txtOverride.Text)
                LogManual("Movie Found ID:" & movieID.ToString)
                populateBackdrops(movieID)
                populatePosters()
                populateMovieInfo()
                btnIncorrectFilm.Visible = True
                pnlIncorrectFilm.Visible = False
                txtOverride.Text = ""
            Else
                searchIMDB(txtOverride.Text, 0)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub TabPage3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TabPage3.Click

    End Sub

    Private Sub btnIncorrectFilm_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnIncorrectFilm.Click
        pnlIncorrectFilm.Visible = True
    End Sub

    Private Sub txtBatchProcess_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtBatchProcess.Enter
        Dim thFolderSelection As New Thread(New ThreadStart(AddressOf FolderBrowserDialog1.ShowDialog))
        thFolderSelection.SetApartmentState(ApartmentState.STA)
        thFolderSelection.IsBackground = True
        thFolderSelection.Start()
        thFolderSelection.Join()
        txtBatchProcess.Text = FolderBrowserDialog1.SelectedPath
    End Sub

    Private Sub chkUnprocessedOnly_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkUnprocessedOnly.CheckedChanged
        populateMovieListBatch()
    End Sub

    Private Sub chkUnprocessedOnlyManual_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkUnprocessedOnlyManual.CheckedChanged
        populateMovieList()
    End Sub

    Private Sub FileSystemWatcher1_Changed(ByVal sender As System.Object, ByVal e As System.IO.FileSystemEventArgs) Handles FileSystemWatcher1.Created, FileSystemWatcher1.Changed, FileSystemWatcher1.Renamed, FileSystemWatcher1.Deleted
        populateMovieList()
        populateMovieListBatch()
    End Sub

    Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
        Application.Exit()
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Application.Exit()
    End Sub
    Delegate Sub UpdateTextHandler(ByVal strMessage As String)

    Private Sub btnEditInfo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEditInfo.Click

        If btnEditInfo.Text = "Hide Movie Info" Then
            pnlMovieInfo.Visible = False
            btnEditInfo.Text = "Edit Movie Info"
        Else
            pnlMovieInfo.Visible = True
            pnlMovieInfo.BringToFront()
            btnEditInfo.Text = "Hide Movie Info"
        End If
    End Sub

    Private Sub searchIMDB(ByVal sMovieName As String, ByVal iUseIMDBId As Integer)
        Try
            LogManual("Searching IMDB for " + sMovieName)
            [error] = False
            imdbMgr = New IMDbManager
            Dim fields() As Boolean = {True, True, True, True, True, True, True, True, True, True, True}

            imdbMgr.parentErrorCaller = formErrorCaller
            imdbMgr.parentFunctionCaller = formFunctionCaller
            imdbMgr.parentProgressUpdaterCaller = formProgressCaller
            imdbMgr.IMDbSearch(iUseIMDBId, sMovieName, 0, -1, 0, 0, fields)
            'imdbMgr.IMDbSearch(1, "tt0458352", 0, -1, 0, 0, fields)
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub
    Private Sub searchIMDBBatch(ByVal sMovieName As String, ByVal iUseIMDBId As Integer)
        Try
            Log("Searching IMDB for " + sMovieName)
            [error] = False
            imdbBatchMgr = New IMDbManager
            Dim fields() As Boolean = {True, True, True, True, True, True, True, True, True, True, True}

            imdbBatchMgr.parentErrorCaller = formBatchErrorCaller
            imdbBatchMgr.parentFunctionCaller = formBatchFunctionCaller
            imdbBatchMgr.parentProgressUpdaterCaller = formBatchProgressCaller
            imdbBatchMgr.IMDbSearch(iUseIMDBId, sMovieName, 0, -1, 0, 0, fields)

            'imdbMgr.IMDbSearch(1, "tt0458352", 0, -1, 0, 0, fields)
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub txtDefaultBackdrop_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtDefaultBackdrop.Enter
        Dim thFolderSelection As New Thread(New ThreadStart(AddressOf OpenFileDialog1.ShowDialog))
        thFolderSelection.SetApartmentState(ApartmentState.STA)
        thFolderSelection.IsBackground = True
        thFolderSelection.Start()
        thFolderSelection.Join()
        'thFolderSelection.
        ' If FolderBrowserDialog1.ShowDialog(Me) = 1 Then
        If OpenFileDialog1.FileName <> vbNullString Then
            txtDefaultBackdrop.Text = OpenFileDialog1.FileName
            My.Settings.DefaultBackdrop = txtDefaultBackdrop.Text
            My.Settings.Save()
        End If
    End Sub

    Private Sub btnSpecifyBackdrop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSpecifyBackdrop.Click
        Try
            Dim thFolderSelection As New Thread(New ThreadStart(AddressOf OpenFileDialog1.ShowDialog))
            thFolderSelection.SetApartmentState(ApartmentState.STA)
            thFolderSelection.IsBackground = True
            thFolderSelection.Start()
            thFolderSelection.Join()
   
            If OpenFileDialog1.FileName <> vbNullString Then
                'load selected backdrop into aryBackdrops
                Dim bmp As New Bitmap(OpenFileDialog1.FileName)
                Dim newBAckdrop = New KeyValuePair(Of Bitmap, String)(bmp, "SelectedBackdrop")
                aryBackdrops.Add(newBAckdrop)
                'lstBackdrops.DataSource=aryBackdrops
            End If
            populateBackdropsList()
            'lstBackdrops.DataSource = Nothing
            'lstBackdrops.DataSource = aryBackdrops
            'lstBackdrops.DisplayMember = "Value"
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub btnSpecifyPoster_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSpecifyPoster.Click
        Try
            Dim thFolderSelection As New Thread(New ThreadStart(AddressOf OpenFileDialog1.ShowDialog))
            thFolderSelection.SetApartmentState(ApartmentState.STA)
            thFolderSelection.IsBackground = True
            thFolderSelection.Start()
            thFolderSelection.Join()

            If OpenFileDialog1.FileName <> vbNullString Then
                'load selected backdrop into aryBackdrops
                Dim bmp As New Bitmap(OpenFileDialog1.FileName)
                Dim newPoster = New KeyValuePair(Of Bitmap, String)(bmp, "SelectedPoster")
                aryPosters.Add(newPoster)
                'lstBackdrops.DataSource=aryBackdrops
            End If
            lstPoster.DataSource = Nothing
            lstPoster.DataSource = aryPosters
            lstPoster.DisplayMember = "Value"
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub btnMoreFound_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMoreFound.Click
        If Results.getInstance.ShowDialog = Windows.Forms.DialogResult.OK Then
            '*********bit of house keeping**********
            bNotFoundOnIMDB = False
            bNotFoundOnMovieDB = False
            txtManualLog.Text = ""
            lstBackdrops.Items.Clear()
            lstPoster.DataSource = Nothing
            pbBackdropPreview.Image = Nothing
            pbPosterPreview.Image = Nothing
            aryBackdrops.Clear()
            aryPosters.Clear()
            Application.DoEvents()
            '**************************************
            imdbMgr.IMDbParse(Results.getInstance.Selected)
        End If
    End Sub

    Private Sub getVideoInfo(ByVal fileName As String)
        bmpAudioFormat = Nothing
        bmpVideoResolution = Nothing
        LogManual("Getting Video & Audio Information")
        Dim s As New Process
        Dim sinf As New ProcessStartInfo
        sinf.FileName = "MediaInfo.exe"
        sinf.Arguments = """" + fileName + """"
        sinf.RedirectStandardOutput = True
        sinf.CreateNoWindow = True
        sinf.UseShellExecute = False
        s = Process.Start(sinf)
        Dim readStream = s.StandardOutput
        Dim sResult = readStream.ReadToEnd

        'detect video
        If fileName.IndexOf("vob") <> -1 Then
            LogManual("DVD File System Detected")
            bmpVideoResolution = New Bitmap(My.Settings.DVDPath)
            bmpAudioFormat = New Bitmap(My.Settings.DolbyPath)
        Else
            If sResult.IndexOf("Width                            : 1 280 pixels") <> -1 Then
                LogManual("720p Video Detected")
                If My.Settings.p720 <> vbNullString Then
                    bmpVideoResolution = New Bitmap(My.Settings.p720)
                Else
                    LogManual("No 720p icon selected.")
                End If
            ElseIf sResult.IndexOf("Width                            : 1 920 pixels") <> -1 Then
                LogManual("1080p Video Detected")
                If My.Settings.p1080 <> vbNullString Then
                    bmpVideoResolution = New Bitmap(My.Settings.p1080)
                Else
                    LogManual("No 1080p icon selected.")
                End If
            ElseIf sResult.IndexOf("XVID") <> -1 Then

                LogManual("Xvid Detected")
                If My.Settings.XvidPath <> vbNullString Then
                    bmpVideoResolution = New Bitmap(My.Settings.XvidPath)
                Else
                    LogManual("No Xvid icon selected")
                End If

            ElseIf sResult.IndexOf("DIVX") <> -1 Then
                LogManual("DIVX Detected")

                If My.Settings.DvixPath <> vbNullString Then
                    bmpVideoResolution = New Bitmap(My.Settings.DvixPath)
                Else
                    LogManual("No DIVX icon selected")
                End If

            End If

            'detect audio
            If sResult.IndexOf("Format                           : AC-3") <> -1 Then
                LogManual("Dolby Digital Detected")
                If My.Settings.DolbyPath <> vbNullString Then
                    bmpAudioFormat = New Bitmap(My.Settings.DolbyPath)
                Else
                    LogManual("No Dolby Digital Icon selected.")
                End If

            ElseIf sResult.IndexOf("Codec ID                         : A_DTS") <> -1 Then
                LogManual("DTS Audio Detected")
                If My.Settings.DTSPath <> vbNullString Then
                    bmpAudioFormat = New Bitmap(My.Settings.DTSPath)
                Else
                    LogManual("No DTS icon selected.")
                End If
            End If
        End If
    End Sub
  
    Private Sub txtDolbyDigital_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtDolbyDigital.Enter
        OpenFileDialog1 = New OpenFileDialog
        Dim thFolderSelection As New Thread(New ThreadStart(AddressOf OpenFileDialog1.ShowDialog))
        thFolderSelection.SetApartmentState(ApartmentState.STA)
        thFolderSelection.IsBackground = True
        thFolderSelection.Start()
        thFolderSelection.Join()

        If OpenFileDialog1.FileName <> vbNullString Then
            txtDolbyDigital.Text = OpenFileDialog1.FileName
            My.Settings.DolbyPath = txtDolbyDigital.Text
        End If
    End Sub

    Private Sub txtDTS_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtDTS.Enter
        Dim thFolderSelection As New Thread(New ThreadStart(AddressOf OpenFileDialog1.ShowDialog))
        thFolderSelection.SetApartmentState(ApartmentState.STA)
        thFolderSelection.IsBackground = True
        thFolderSelection.Start()
        thFolderSelection.Join()

        If OpenFileDialog1.FileName <> vbNullString Then
            txtDTS.Text = OpenFileDialog1.FileName
            My.Settings.DTSPath = txtDTS.Text
        End If
    End Sub

    Private Sub txt720_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles txt720.Enter
        Dim thFolderSelection As New Thread(New ThreadStart(AddressOf OpenFileDialog1.ShowDialog))
        thFolderSelection.SetApartmentState(ApartmentState.STA)
        thFolderSelection.IsBackground = True
        thFolderSelection.Start()
        thFolderSelection.Join()

        If OpenFileDialog1.FileName <> vbNullString Then
            txt720.Text = OpenFileDialog1.FileName
            My.Settings.p720 = txt720.Text
        End If
    End Sub

    Private Sub txt1080_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles txt1080.Enter
        Dim thFolderSelection As New Thread(New ThreadStart(AddressOf OpenFileDialog1.ShowDialog))
        thFolderSelection.SetApartmentState(ApartmentState.STA)
        thFolderSelection.IsBackground = True
        thFolderSelection.Start()
        thFolderSelection.Join()

        If OpenFileDialog1.FileName <> vbNullString Then
            txt1080.Text = OpenFileDialog1.FileName
            My.Settings.p1080 = txt1080.Text
        End If
    End Sub

    Private Sub btnRedo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRedo.Click
        Try
            Dim s As KeyValuePair(Of String, String)
            s = lstMovies.SelectedItem
            pnlApplyTemplate.Visible = False
            pbExistingSheet.Visible = False
            pnlCreateSheet.Visible = True
            btnRedo.Visible = False
            pbExistingSheet.Image.Dispose()
            pbExistingSheet.Image = Nothing
            '*********bit of house keeping**********
            bNotFoundOnIMDB = False
            bNotFoundOnMovieDB = False
            txtManualLog.Text = ""
            lstBackdrops.Items.Clear()
            lstPoster.DataSource = Nothing
            pbBackdropPreview.Image = Nothing
            pbPosterPreview.Image = Nothing
            aryBackdrops.Clear()
            aryPosters.Clear()
            btnMoreFound.Visible = False
            Application.DoEvents()
            '**************************************
            Cursor.Current = Cursors.WaitCursor
            btnIncorrectFilm.Visible = True
            If My.Settings.PrimarySource = "MovieDB" Then
                Dim movieID = searchForMovie(s.Value)
                If movieID <> 0 Then
                    LogManual("Movie Found ID:" & movieID.ToString)
                    populateBackdrops(movieID)
                    populatePosters()
                    populateMovieInfo()
                    Application.DoEvents()
                    btnIncorrectFilm.Visible = True
                Else
                    ' MessageBox.Show("Movie Not Found")
                    btnIncorrectFilm.Visible = True
                End If
            Else
                'use IMDB as primary source
                searchIMDB(s.Value, 0)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub
    'IB 24/08/09 Test TVIXiE Template support code
    Private Function ApplyTemplate(ByVal sPath As String, ByVal bmpBackDrop As Bitmap, ByVal bmpCover As Bitmap) As Bitmap
        Try
            '******************
            Cursor.Current = Cursors.WaitCursor
            Dim s As New KeyValuePair(Of String, String)
            ' Dim selectedBackdrop As New KeyValuePair(Of Bitmap, String)
            '  Dim selectedPoster As New KeyValuePair(Of Bitmap, String)
            '   selectedBackdrop = lstBackdrops.SelectedItems(0).Tag
            '   selectedPoster = lstPoster.SelectedItem
            s = lstMovies.SelectedItem

          
            '************************************************************************************
            Dim doc As New XDocument
            Dim fs As New IO.FileStream(sPath, IO.FileMode.Open)
            Dim reader As New XmlTextReader(fs)
            doc = XDocument.Load(reader)
            Dim textElements = From c In doc.Elements("Template").Elements("ImageDrawTemplate").Elements("Elements").Elements("TextElement") _
                         Select c
            Dim imageElements = From c In doc.Elements("Template").Elements("ImageDrawTemplate").Elements("Elements").Elements("ImageElement") _
                         Select c
            Dim imageSettings = From c In doc.Elements("Template").Elements("ImageDrawTemplate").Elements("OutputImageSettings") _
                         Select c
            Dim templateSettings = From c In doc.Elements("Template").Elements("Settings") _
                         Select c
            '************************************************************
            'Draw Image using template
            fs.Close()
            Dim newbitmap As New Bitmap(1280, 720, Imaging.PixelFormat.Format32bppArgb)
            Dim dpi As Integer = CInt(imageSettings.Attributes("Dpi")(0).Value)
            Dim path = sPath.Replace("\Template.xml", "")
            newbitmap.SetResolution(dpi, dpi)
            Dim ratingIcon As Bitmap = Nothing
            Dim sActorSeprator As Char = ""
            Dim iNumActors As Integer = 0
            Dim sGenresSeprator As Char = ""
            Dim iNumGenres As Integer = 0
            Dim sRatingIconPath As String = ""
            For Each setting In templateSettings
                sActorSeprator = setting.Element("Actors").Attribute("Separator").Value
                iNumActors = CInt(setting.Element("Actors").Attribute("MaximumValues").Value)
                iNumGenres = CInt(setting.Element("Genres").Attribute("MaximumValues").Value)
                sGenresSeprator = setting.Element("Genres").Attribute("Separator").Value
                sRatingIconPath = setting.Element("Rating").Attribute("FileName").Value.Replace("%PATH%", "")
                Application.DoEvents()
            Next


            ratingIcon = New Bitmap(path & sRatingIconPath)
          

            Dim g As Graphics
            g = Graphics.FromImage(newbitmap)
            g.Clear(Color.Black)
            g.SmoothingMode = Drawing2D.SmoothingMode.HighQuality
            g.TextRenderingHint = Drawing.Text.TextRenderingHint.AntiAliasGridFit


            For Each img In imageElements
                ' If img.Attribute("SourceData").Value <> "%RATINGSTARS%" Then
                Dim imgRect As Rectangle
                If img.Attribute("Name").Value = "Background" Then
                    imgRect = New Rectangle(0, 0, 1280, 720)
                Else
                    imgRect = New Rectangle(img.Attribute("X").Value, img.Attribute("Y").Value, img.Attribute("Width").Value, img.Attribute("Height").Value)
                End If
                If img.Attribute("Source").Value = "File" Then
                    Dim sourcePath = img.Attribute("SourceData").Value.Replace("%PATH%", path)
                    Dim newBmp As Bitmap
                    If img.Attribute("SourceData").Value = "%COVER%" Then
                        newBmp = bmpCover
                    Else
                        newBmp = New Bitmap(sourcePath)
                    End If

                    If img.Attribute("SourceData").Value.IndexOf("BACKDROP") <> -1 Then
                        newBmp = bmpBackDrop
                    End If
                    If img.Attribute("SourceData").Value.IndexOf("FANART") <> -1 And bmpFanArt1 IsNot Nothing Then
                        newBmp = bmpFanArt1
                    End If
                    If img.Attribute("SourceData").Value.IndexOf("thumb1") <> -1 And bmpFanArt2 IsNot Nothing Then
                        newBmp = bmpFanArt2
                    End If
                    If img.Attribute("SourceData").Value.IndexOf("thumb2") <> -1 And bmpFanArt3 IsNot Nothing Then
                        newBmp = bmpFanArt3
                    End If
                    If img.Attribute("Name").Value.Equals("ResolutionINFO") Then
                        If bmpVideoResolution IsNot Nothing Then
                            newBmp = bmpVideoResolution
                        Else
                            newBmp = Nothing
                        End If
                    End If
                    If img.Attribute("Name").Value.Equals("AudioCodecINFO") Then
                        If bmpAudioFormat IsNot Nothing Then
                            newBmp = bmpAudioFormat
                        Else
                            newBmp = Nothing
                        End If
                    End If
                    If newBmp IsNot Nothing Then
                        g.DrawImage(newBmp, imgRect)
                    End If
                Else
                    If img.Attribute("SourceData").Value.Equals("%RATINGSTARS%") Then
                        Dim newRating As New Bitmap(120, 24)
                        Dim g1 As Graphics
                        g1 = Graphics.FromImage(newRating)
                        Dim imgRect1 As New Rectangle(0, 0, 24, 24)
                        Dim imgRect2 As New Rectangle(24, 0, 24, 24)
                        Dim imgRect3 As New Rectangle(48, 0, 24, 24)
                        Dim imgRect4 As New Rectangle(72, 0, 24, 24)
                        Dim imgRect5 As New Rectangle(96, 0, 24, 24)

                        g1.DrawImage(ratingIcon, imgRect1)
                        g1.DrawImage(ratingIcon, imgRect2)
                        g1.DrawImage(ratingIcon, imgRect3)
                        g1.DrawImage(ratingIcon, imgRect4)
                        g1.DrawImage(ratingIcon, imgRect5)



                        Dim rating = CDbl(txtRating.Text.Split("/")(0))
                        Dim pixelsToShow = (rating * 10) * 1.2
                        Dim newRect = imgRect
                        newRect.Width = pixelsToShow
                        'g1.Clip = New Region(New Rectangle(10, 10, 20, newRect.Height))

                        g.DrawImage(newRating, newRect, New Rectangle(0, 0, newRect.Width, newRect.Height), GraphicsUnit.Pixel)

                    End If


                End If
                ' End If
            Next

            For Each txt In textElements
                Dim sText As String = ""
                Dim sFontInfo() As String = txt.Attribute("Font").Value.Split(",")
                Dim size = CInt(sFontInfo(1))
                Dim iStyle As Integer = 0
                If sFontInfo.Length = 9 Then

                    If sFontInfo(2) = "True" Then
                        iStyle = FontStyle.Bold
                    ElseIf sFontInfo(3) = "True" Then
                        iStyle = FontStyle.Italic
                    ElseIf sFontInfo(4) = "True" Then
                        iStyle = FontStyle.Underline
                    ElseIf sFontInfo(5) = "True" Then
                        iStyle = FontStyle.Strikeout
                    End If
                End If
                Dim sf As New StringFormat
                If txt.Attribute("TextAlignment").Value.IndexOf("Center") <> -1 Then
                    sf.Alignment = StringAlignment.Center
                ElseIf txt.Attribute("TextAlignment").Value.IndexOf("Left") <> -1 Then
                    sf.Alignment = StringAlignment.Near
                ElseIf txt.Attribute("TextAlignment").Value.IndexOf("Right") <> -1 Then
                    sf.Alignment = StringAlignment.Far
                End If
                Dim f As New Font(sFontInfo(0), size, iStyle, GraphicsUnit.Point)
                Dim txtRect As New Rectangle(txt.Attribute("X").Value, txt.Attribute("Y").Value, txt.Attribute("Width").Value, txt.Attribute("Height").Value)

                sText = txt.Attribute("Text").Value
                If txt.Attribute("Text").Value.IndexOf("%PLOT%") <> -1 Then
                    sText = txt.Attribute("Text").Value.Replace("%PLOT%", txtSummary.Text)
                End If
                If txt.Attribute("Text").Value.IndexOf("%TITLE%") <> -1 Then
                    If sText = vbNullString Then
                        sText = txt.Attribute("Text").Value.Replace("%TITLE%", txtTitle.Text)
                    Else
                        sText = sText.Replace("%TITLE%", txtTitle.Text)
                    End If

                End If

                If txt.Attribute("Text").Value.IndexOf("%YEAR%") <> -1 Then
                    If sText = vbNullString Then
                        sText = txt.Attribute("Text").Value.Replace("%YEAR%", txtYear.Text)
                    Else
                        sText = sText.Replace("%YEAR%", txtYear.Text)
                    End If

                End If
                If txt.Attribute("Text").Value.IndexOf("%ACTORS%") <> -1 Then
                    Dim sActorsToShow As New System.Text.StringBuilder

                    Dim sActors = txtActors.Text.Split(",")
                    Dim iLimit As Integer = 0
                    If sActors.Length > iNumGenres Then
                        iLimit = iNumActors
                    Else
                        iLimit = sActors.Length
                    End If
                    For i As Integer = 0 To iNumActors - 1 Step 1
                        If sActors(i).Trim <> vbNullString Then
                            If i = 0 Then
                                sActorsToShow.Append(sActors(i))
                            Else
                                sActorsToShow.Append(sActorSeprator & sActors(i))
                            End If
                        End If
                    Next
                    If sText = vbNullString Then
                        sText = txt.Attribute("Text").Value.Replace("%ACTORS%", sActorsToShow.ToString)
                    Else
                        sText = sText.Replace("%ACTORS%", sActorsToShow.ToString)
                    End If

                End If



                If txt.Attribute("Text").Value.IndexOf("%GENRES%") <> -1 Then
                    Dim sGenresToShow As New System.Text.StringBuilder

                    Dim sGenres = txtGenres.Text.Split(",")
                    Dim iLimit As Integer = 0
                    If sGenres.Length > iNumGenres Then
                        iLimit = iNumGenres
                    Else
                        iLimit = sGenres.Length
                    End If
                    For i As Integer = 0 To iLimit - 1 Step 1
                        If sGenres(i).Trim <> vbNullString Then
                            If i = 0 Then
                                sGenresToShow.Append(sGenres(i))
                            Else
                                sGenresToShow.Append(sGenresSeprator & sGenres(i))
                            End If
                        End If
                    Next
                    If sText = vbNullString Then
                        sText = txt.Attribute("Text").Value.Replace("%GENRES%", sGenresToShow.ToString)
                    Else
                        sText = sText.Replace("%GENRES%", sGenresToShow.ToString)
                    End If

                End If
                If txt.Attribute("Text").Value.IndexOf("%DIRECTORS%") <> -1 Then

                    If sText = vbNullString Then
                        sText = txt.Attribute("Text").Value.Replace("%DIRECTORS%", txtDirectors.Text)
                    Else
                        sText = sText.Replace("%DIRECTORS%", txtDirectors.Text)
                    End If

                End If
                If txt.Attribute("Text").Value.IndexOf("%RUNTIME%") <> -1 Then
                    sText = txt.Attribute("Text").Value.Replace("%RUNTIME%", txtRunTime.Text.Replace("min", ""))
                End If
                If txt.Attribute("Text").Value.IndexOf("%RATING%") <> -1 Then
                    sText = txt.Attribute("Text").Value.Replace("%RATING%", txtRating.Text)
                End If
                'trim  string till it fits on one line
                If txt.Attribute("Multiline").Value.Equals("False") And txt.Attribute("AutoSize").Value.Equals("False") Then
                    Dim bApplyEndString As Boolean = False
                    Dim i As Integer = 1
                    If sText <> vbNullString And txtRect.Width <> 0 Then
                        Dim sizeTrimForDots = TextRenderer.MeasureText("...", f)
                        'allow for a little bit bigger
                        If TextRenderer.MeasureText(sText, f).Width > txtRect.Width + 5 Then
                            While TextRenderer.MeasureText(sText, f, New Size(txtRect.Width, txtRect.Height)).Width > txtRect.Width - sizeTrimForDots.Width
                                sText = sText.Substring(0, sText.Length - i)
                                bApplyEndString = True
                            End While
                        End If
                        If bApplyEndString Then
                            sText = sText & "..."
                        End If
                        If TextRenderer.MeasureText(sText, f).Height > txtRect.Height + 5 = False Then

                            txtRect.Height = TextRenderer.MeasureText(sText, f).Height
                        End If
                    End If
                ElseIf txt.Attribute("AutoSize").Value.Equals("True") Then
                    txtRect.Width = 0
                    txtRect.Height = 0
                End If
                Dim myBrush As New SolidBrush(ColorTranslator.FromOle(CInt(txt.Attribute("ForeColor").Value)))
                'bug in tvixie maps wrong color values to RGB pallette.
                Dim correctColor As Color = Color.FromArgb(255, myBrush.Color.B, myBrush.Color.G, myBrush.Color.R)
                myBrush.Color = correctColor
                g.SmoothingMode = Drawing2D.SmoothingMode.HighQuality
                g.TextRenderingHint = Drawing.Text.TextRenderingHint.AntiAliasGridFit
                g.DrawString(sText, f, myBrush, txtRect, sf)
            Next
            Application.DoEvents()
            Return newbitmap
        Catch ex As Exception
            MessageBox.Show(ex.Message)
            Return Nothing
        End Try
    End Function

 

  

    Private Sub btnAddTemplate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddTemplate.Click
        Try
            Dim sTemplatePath = txtSelectTemplate.Text
            Dim sTemplateName As String = ""
            'get template name from path
            Dim sFolders = sTemplatePath.Split("\")
            sTemplateName = sFolders(sFolders.Length - 2)

            Dim newLstViewItem As New ListViewItem
            newLstViewItem.Text = sTemplateName
            newLstViewItem.SubItems.Add(sTemplatePath)
            lstTemplates.Items.Add(newLstViewItem)
            saveTemplates()
            cboTemplates.DataSource = Nothing
            cboTemplates.DataSource = lstTemplates.Items
            cboTemplates.DisplayMember = "Text"
            cboTemplates.SelectedIndex = getDefualtLocation()
            cboApplyNewTemplate.DataSource = Nothing

            cboApplyNewTemplate.DataSource = lstTemplates.Items
            cboApplyNewTemplate.DisplayMember = "Text"
            cboApplyNewTemplate.SelectedIndex = getDefualtLocation()
            previewNewTemplate(sTemplatePath)
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub
    Private Sub previewNewTemplate(ByVal sTemplatePath As String)
        Try
            'Dim sampleImage=ApplyTemplate(sTemplatePath
            Dim s As New KeyValuePair(Of String, String)(IO.Path.GetDirectoryName(Application.ExecutablePath) & "\Sample\", "")

            If IO.File.Exists(s.Key & "\Movie_Info.xml") Then
                LoadXML(s.Key & "\Movie_Info.xml")
                Dim bmpBackdropLocal As New Bitmap(s.Key & "\backdrop.jpg")
                Dim bmpCoverLocal As New Bitmap(s.Key & "\cover.jpg")
                If IO.File.Exists(s.Key & "\fanart1.jpg") Then
                    bmpFanArt1 = New Bitmap(s.Key & "\fanart1.jpg")
                Else
                    bmpFanArt1 = Nothing
                End If
                If IO.File.Exists(s.Key & "\fanart2.jpg") Then
                    bmpFanArt2 = New Bitmap(s.Key & "\fanart2.jpg")
                Else
                    bmpFanArt2 = Nothing
                End If
                If IO.File.Exists(s.Key & "\fanart3.jpg") Then
                    bmpFanArt3 = New Bitmap(s.Key & "\fanart3.jpg")
                Else
                    bmpFanArt3 = Nothing
                End If
                bmpVideoResolution = My.Resources.Images.HD_1080P_1
                bmpAudioFormat = My.Resources.Images.DTS_white
                createdImage = ApplyTemplate(sTemplatePath, bmpBackdropLocal, bmpCoverLocal)
                pbPreview.Image = createdImage
                createdImage.Save(sTemplatePath.Replace("Template.xml", "") & "wdtv_preview.jpg")
                Application.DoEvents()
                bmpVideoResolution = Nothing
                bmpAudioFormat = Nothing
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub
    Private Sub btnMakeDefault_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMakeDefault.Click
        Try
            For Each item As ListViewItem In lstTemplates.Items
                item.BackColor = Color.White
                item.SubItems(1).Text = item.SubItems(1).Text.Replace("*", "")
            Next
            lstTemplates.Items(lstTemplates.SelectedIndices(0)).BackColor = Color.SkyBlue
            sDefaultTemplatePath = lstTemplates.Items(lstTemplates.SelectedIndices(0)).SubItems(1).Text
            lstTemplates.Items(lstTemplates.SelectedIndices(0)).SubItems(1).Text = "*" & lstTemplates.Items(lstTemplates.SelectedIndices(0)).SubItems(1).Text

            saveTemplates()
            cboTemplates.SelectedIndex = getDefualtLocation()
            cboApplyNewTemplate.SelectedIndex = getDefualtLocation()
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub saveTemplates()
        Try
            Dim sTemplates As String = ""
            For Each template As ListViewItem In lstTemplates.Items
                sTemplates = sTemplates & template.SubItems(1).Text & ";"
            Next
            My.Settings.SavedTemplates = sTemplates
            My.Settings.Save()
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub
    Private Function getDefualtLocation()
        Try
            Dim q = (From lvi As ListViewItem In lstTemplates.Items _
                    Where lvi.BackColor = Color.SkyBlue _
                    Select lvi.Index).FirstOrDefault
            Return q
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Function
    Private Sub loadSavedTemplates()
        Try
            'now load the templates storeds in the settings file
            Dim sTemplates = My.Settings.SavedTemplates.Split(";")
            For Each sTemplate In sTemplates
                If sTemplate <> vbNullString Then
                    Dim sTemplateName As String = ""
                    'get template name from path
                    Dim sFolders = sTemplate.Split("\")
                    sTemplateName = sFolders(sFolders.Length - 2)

                    Dim newItem As New ListViewItem
                    newItem.Text = sTemplateName
                    newItem.SubItems.Add(sTemplate)
                    If sTemplate.IndexOf("*") <> -1 Then
                        newItem.BackColor = Color.SkyBlue
                        sDefaultTemplatePath = sTemplate.Replace("*", "")
                    End If
                    lstTemplates.Items.Add(newItem)
                End If
            Next
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRemoveTemplate.Click
        Try
            lstTemplates.Items.RemoveAt(lstTemplates.SelectedIndices(0))
            saveTemplates()
            cboTemplates.DataSource = Nothing
            cboTemplates.DataSource = lstTemplates.Items
            cboTemplates.DisplayMember = "Text"
            cboTemplates.SelectedIndex = getDefualtLocation()
            cboApplyNewTemplate.DataSource = Nothing

            cboApplyNewTemplate.DataSource = lstTemplates.Items
            cboApplyNewTemplate.DisplayMember = "Text"
            cboApplyNewTemplate.SelectedIndex = getDefualtLocation()
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub chkUseOriginal_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkUseOriginal.CheckedChanged
        If chkUseOriginal.Checked Then
            lstTemplates.Enabled = False
            cboTemplates.Visible = False
            lblTemplates.Visible = False

        Else
            lblTemplates.Visible = True
            lstTemplates.Enabled = True
            cboTemplates.Visible = True

        End If
        My.Settings.UseOriginal = chkUseOriginal.Checked
        My.Settings.Save()
    End Sub

    Private Sub LoadXML(ByVal sXMLPath As String)
        Try
            Dim doc As New XDocument
            Dim reader As New XmlTextReader(sXMLPath)
            doc = XDocument.Load(reader)
            Dim q = From c In doc.Elements("Movie") _
               Select c
            Dim firstOBJ = q.ElementAt(0)
            'populate new currentTitle object
            currentTitle = New IMDbTitle
            With currentTitle
                txtTitle.Text = firstOBJ.Attribute("Title").Value.ToString
                txtYear.Text = firstOBJ.Attribute("Year").Value.ToString
                txtSummary.Text = firstOBJ.Attribute("Plot").Value.ToString
                txtRunTime.Text = firstOBJ.Attribute("Runtime").Value.ToString
                txtRating.Text = firstOBJ.Attribute("Rating").Value.ToString()
                If firstOBJ.Attribute("Actors") IsNot Nothing Then
                    txtActors.Text = firstOBJ.Attribute("Actors").Value.ToString
                End If

                If firstOBJ.Attribute("Directors") IsNot Nothing Then
                    txtDirectors.Text = firstOBJ.Attribute("Directors").Value.ToString
                End If
                If firstOBJ.Attribute("Genres") IsNot Nothing Then
                    txtGenres.Text = firstOBJ.Attribute("Genres").Value.ToString
                End If

            End With
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub
    Private Sub btnRedoWithTemplate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRedoWithTemplate.Click
        Try
            'load cached info
            Dim s As KeyValuePair(Of String, String)
            s = lstMovies.SelectedItem
            'first check and show any existing moviesheet
            If IO.File.Exists(s.Key & "\Movie_Info.xml") Then
                'LoadXML(s.Key & "\Movie_Info.xml")
                Dim bmpBackdropLocal As New Bitmap(s.Key & "\backdrop.jpg")
                Dim bmpCoverLocal As New Bitmap(s.Key & "\cover.jpg")
                If IO.File.Exists(s.Key & "\fanart1.jpg") Then
                    bmpFanArt1 = New Bitmap(s.Key & "\fanart1.jpg")
                Else
                    bmpFanArt1 = Nothing
                End If
                If IO.File.Exists(s.Key & "\fanart2.jpg") Then
                    bmpFanArt2 = New Bitmap(s.Key & "\fanart2.jpg")
                Else
                    bmpFanArt2 = Nothing
                End If
                If IO.File.Exists(s.Key & "\fanart3.jpg") Then
                    bmpFanArt3 = New Bitmap(s.Key & "\fanart3.jpg")
                Else
                    bmpFanArt3 = Nothing
                End If
                pbExistingSheet.Image.Dispose()
                pbExistingSheet.Image = Nothing
                If My.Settings.AnalyseMKVs Then
                    Dim direcInfo As New IO.DirectoryInfo(s.Key)
                    Dim fileAry As New List(Of IO.FileInfo)
                    Dim targetFile As String
                    fileAry.AddRange(direcInfo.GetFiles("*.mkv"))
                    fileAry.AddRange(direcInfo.GetFiles("*.avi"))
                    fileAry.AddRange(direcInfo.GetFiles("*.wmv"))
                    fileAry.AddRange(direcInfo.GetFiles("*.vob"))
                    Dim maxSize As Long = 0
                    For Each f In fileAry
                        If f.Length > maxSize Then
                            targetFile = f.FullName
                        End If
                    Next
                    If targetFile <> vbNullString Then
                        getVideoInfo(targetFile)
                    End If
                End If
                'get path of selected template
                Dim overridePath = (From lvi As ListViewItem In lstTemplates.Items _
                       Where lvi.Text = cboApplyNewTemplate.Text _
                       Select lvi.SubItems(1).Text).FirstOrDefault
                overridePath = overridePath.Replace("*", "")
                createdImage = ApplyTemplate(overridePath, bmpBackdropLocal, bmpCoverLocal)

                pbExistingSheet.Image = createdImage
                createdImage.Save(s.Key & "\" & My.Settings.MovieSheetName, Imaging.ImageFormat.Jpeg)
                Application.DoEvents()
            Else
                MessageBox.Show("There is no cached information stored on this movie. Press 'ReDo' and generate a new movie sheet. This will create a cache of data for this movie")
            End If

        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub btnEditMovieInfo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEditMovieInfo.Click
        If btnEditMovieInfo.Text = "Edit Movie Info" Then
            pnlMovieInfo.Visible = True
            btnEditMovieInfo.Text = "Hide Movie Info"
            pnlMovieInfo.BringToFront()
            pbExistingSheet.Size = New Size(pbExistingSheet.Size.Width / 2, pbExistingSheet.Size.Width / 2)
        Else
            pnlMovieInfo.Visible = False
            btnEditMovieInfo.Text = "Edit Movie Info"
            pbExistingSheet.Size = New Size(960, 540)
        End If
    End Sub
    Private Sub btnBrowse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBrowse.Click
        Try
            OpenFileDialog1 = New OpenFileDialog
            OpenFileDialog1.Filter = "XML Files (*.xml)|*.xml;"

            Dim thFolderSelection As New Thread(New ThreadStart(AddressOf OpenFileDialog1.ShowDialog))
            thFolderSelection.SetApartmentState(ApartmentState.STA)
            thFolderSelection.IsBackground = True
            thFolderSelection.Start()
            thFolderSelection.Join()


            If OpenFileDialog1.FileName <> vbNullString Then
                txtSelectTemplate.Text = OpenFileDialog1.FileName
            End If
            OpenFileDialog1.Filter = ""
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub mnuFanArt1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles mnuFanArt1.Click
        Try
            If mnuFanArt1.Checked = False Then
                lstBackdrops.SelectedItems(0).BackColor = Color.Blue
                mnuFanArt1.Checked = True
                Dim s As KeyValuePair(Of Bitmap, String) = lstBackdrops.SelectedItems(0).Tag
                bmpFanArt1 = New Bitmap(s.key)
            ElseIf lstBackdrops.SelectedItems(0).BackColor = Color.Blue Then
                mnuFanArt1.Checked = False
                lstBackdrops.SelectedItems(0).BackColor = Color.White
            Else
                For Each lvi As ListViewItem In lstBackdrops.Items
                    If lvi.BackColor = Color.Blue Then
                        lvi.BackColor = Color.White
                    End If
                Next
                lstBackdrops.SelectedItems(0).BackColor = Color.Blue
                Dim s As KeyValuePair(Of Bitmap, String) = lstBackdrops.SelectedItems(0).Tag
                bmpFanArt1 = New Bitmap(s.Key)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub ContextMenuStrip1_Opening(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles ContextMenuStrip1.Opening
        Try
            If lstBackdrops.Items.Count = 0 Then
                e.Cancel = True
            ElseIf lstBackdrops.SelectedItems.Count <> 1 Then
                e.Cancel = True

            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub mnuFanArt2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles mnuFanArt2.Click
        Try
            If mnuFanArt2.Checked = False Then
                lstBackdrops.SelectedItems(0).BackColor = Color.Red
                mnuFanArt2.Checked = True
                Dim s As KeyValuePair(Of Bitmap, String) = lstBackdrops.SelectedItems(0).Tag
                bmpFanArt2 = New Bitmap(s.Key)
            ElseIf lstBackdrops.SelectedItems(0).BackColor = Color.Red Then
                mnuFanArt2.Checked = False
                lstBackdrops.SelectedItems(0).BackColor = Color.White
            Else
                For Each lvi As ListViewItem In lstBackdrops.Items
                    If lvi.BackColor = Color.Red Then
                        lvi.BackColor = Color.White
                    End If
                Next
                lstBackdrops.SelectedItems(0).BackColor = Color.Red
                Dim s As KeyValuePair(Of Bitmap, String) = lstBackdrops.SelectedItems(0).Tag
                bmpFanArt2 = New Bitmap(s.Key)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub mnuFanArt3_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles mnuFanArt3.Click
        Try
            If mnuFanArt3.Checked = False Then
                lstBackdrops.SelectedItems(0).BackColor = Color.Green
                mnuFanArt3.Checked = True
                Dim s As KeyValuePair(Of Bitmap, String) = lstBackdrops.SelectedItems(0).Tag
                bmpFanArt3 = New Bitmap(s.Key)
            ElseIf lstBackdrops.SelectedItems(0).BackColor = Color.Green Then
                mnuFanArt3.Checked = False
                lstBackdrops.SelectedItems(0).BackColor = Color.White
            Else

                For Each lvi As ListViewItem In lstBackdrops.Items
                    If lvi.BackColor = Color.Green Then
                        lvi.BackColor = Color.White
                    End If
                Next
                lstBackdrops.SelectedItems(0).BackColor = Color.Green
                Dim s As KeyValuePair(Of Bitmap, String) = lstBackdrops.SelectedItems(0).Tag
                bmpFanArt3 = New Bitmap(s.Key)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub btnClearFanArt_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClearFanArt.Click
        clearFanArt()
        For Each lvi As ListViewItem In lstBackdrops.Items
            lvi.BackColor = Color.White
        Next
    End Sub

    Private Sub txtDVDIcon_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtDVDIcon.Enter
        Dim thFolderSelection As New Thread(New ThreadStart(AddressOf OpenFileDialog1.ShowDialog))
        thFolderSelection.SetApartmentState(ApartmentState.STA)
        thFolderSelection.IsBackground = True
        thFolderSelection.Start()
        thFolderSelection.Join()

        If OpenFileDialog1.FileName <> vbNullString Then
            txtDVDIcon.Text = OpenFileDialog1.FileName
            My.Settings.DVDPath = txtDVDIcon.Text
        End If
    End Sub

    Private Sub txtXvidIcon_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtXvidIcon.Enter
        OpenFileDialog1 = New OpenFileDialog
        Dim thFolderSelection As New Thread(New ThreadStart(AddressOf OpenFileDialog1.ShowDialog))
        thFolderSelection.SetApartmentState(ApartmentState.STA)
        thFolderSelection.IsBackground = True
        thFolderSelection.Start()
        thFolderSelection.Join()

        If OpenFileDialog1.FileName <> vbNullString Then
            txtXvidIcon.Text = OpenFileDialog1.FileName
            My.Settings.XvidPath = txtXvidIcon.Text
        End If
    End Sub

    Private Sub txtDivxIcon_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtDivxIcon.Enter
        OpenFileDialog1 = New OpenFileDialog
        Dim thFolderSelection As New Thread(New ThreadStart(AddressOf OpenFileDialog1.ShowDialog))
        thFolderSelection.SetApartmentState(ApartmentState.STA)
        thFolderSelection.IsBackground = True
        thFolderSelection.Start()
        thFolderSelection.Join()

        If OpenFileDialog1.FileName <> vbNullString Then
            txtDivxIcon.Text = OpenFileDialog1.FileName
            My.Settings.DvixPath = txtDivxIcon.Text
        End If
    End Sub

    Private Sub TabControl1_TabIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TabControl1.SelectedIndexChanged
        If TabControl1.SelectedIndex <> 0 Then
            pnlMovieInfo.Visible = False
            btnEditMovieInfo.Text = "Edit Movie Info"
            pbExistingSheet.Size = New Size(960, 540)
            btnEditInfo.Text = "Edit Movie Info"
        End If
    End Sub

    Private Sub lstTemplates_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles lstTemplates.SelectedIndexChanged
        Try
            Dim newBmp As Bitmap
            Dim sTemplateLocation As String = ""
            If lstTemplates.SelectedIndices.Count > 0 Then
                sTemplateLocation = lstTemplates.Items(lstTemplates.SelectedIndices(0)).SubItems(1).Text.Replace("*", "")
                sTemplateLocation = sTemplateLocation.Replace("Template.xml", "")
                sTemplateLocation = sTemplateLocation & "wdtv_preview.jpg"
                If IO.File.Exists(sTemplateLocation) Then
                    newBmp = New Bitmap(sTemplateLocation)
                    pbPreview.Image = newBmp
                    Application.DoEvents()
                Else
                    pbPreview.Image = Nothing
                End If
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub
End Class
